I've been trying hard on this for a while now, but can't find a solution on how to convert json to xml in php by file_get_contents. I don't want to use an online converter but want to have it in my website root directory. Thanks in advance!
Asked
Active
Viewed 1,479 times
0
-
2check http://stackoverflow.com/questions/856833/is-there-some-way-to-convert-json-to-xml-in-php – air4x Nov 13 '12 at 13:55
-
http://stackoverflow.com/questions/4345445/how-to-convert-json-to-xml-in-php Please do a search before asking a question. =o) – kittycat Nov 13 '12 at 13:56
1 Answers
2
You can convert JSON to array/object by using json_decode()
, once you have it inside array you can use any XML Manipulation method to build XML out of it.
For example you may build XML structure like this:
<array>
<data name="atrribute1">string 1</data>
<array name="array_atribute">
<data name="attribute2">string 2</data>
<data name="attribute2">string 2</data>
</array>
</array>
By DOMDocument
, and method DOMDocument::createElement()
class XMLSerialize {
protected $dom = null;
public function serialize( $array)
{
$this->dom = new DOMDocument('1.0', 'utf-8');
$element = $this->dom->createElement('array');
$this->dom->appendChild($element);
$this->addData( $element, $array);
}
protected function addData( DOMElement &$element, $array)
{
foreach($array as $k => $v){
$e = null;
if( is_array( $v)){
// Add recursive data
$e = $this->dom->createElement( 'array', $v);
$e->setAttribute( 'name', $k);
$this->addData( $e, $v);
} else {
// Add linear data
$e = $this->dom->createElement( 'data', $v);
$e->setAttribute( 'name', $k);
}
$element->appendChild($e);
}
}
public function get_xml()
{
return $this->dom->saveXML();
}
}

Vyktor
- 20,559
- 6
- 64
- 96