Tuesday, October 4, 2011

php Associate array to XML and JSON

PHP 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
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <hoge>123</hoge>
    <foo>456</foo>
    <bar>789</bar>
    <aaa>
        <abc>111</abc>
        <bcd>222</bcd>
        <cde>333</cde>
    </aaa>
    <bbb>
        <def>
            <efg>hoge</efg>
        </def>
    </bbb>
</root>


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

No comments: