DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Associate Array To XML And JSON

01.30.2007
| 38517 views |
  • submit to reddit
        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