Never been to DZone Snippets before?

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

Associate array to XML and JSON (See related posts)

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

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts