Reputation: 17
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!
Upvotes: 0
Views: 1486
Reputation: 21007
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();
}
}
Upvotes: 2