Associate Array To XML And JSON
Join the DZone community and get the full member experience.
Join For FreePHP Associate array data
$data = array(
"hoge" => 123,
"foo" => 456,
"bar" => 789,
"aaa" => array(
"abc" => 111,
"bcd" => 222,
"cde" => 333
),
"bbb" => array(
"def" => array(
"efg" => "hoge"
)
)
);
to XML
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('root');
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $data);
$xml->endElement();
echo $xml->outputMemory(true);
output XML
123
456
789
111
222
333
hoge
to JSON
echo json_encode($data);
output JSON
{
"hoge":123,
"foo":456,
"bar":789,
"aaa":{
"abc":111,
"bcd":222,
"cde":333
},
"bbb":{
"def":{
"efg":"hoge"
}
}
}
Requires PHP5.2.x or xmlwriter extension, json extension
XML
JSON
Opinions expressed by DZone contributors are their own.
Comments