Platinum Partner

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



    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
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}