Reputation: 63
I need to convert json format to xml using laravel. I'm expecting output like following.
<MESSAGE>
<AUTHKEY>Your auth key</AUTHKEY>
<SENDER>SenderID</SENDER>
<ROUTE>Template</ROUTE>
<CAMPAIGN>campaign name</CAMPAIGN>
<COUNTRY>country code</COUNTRY>
<SMS TEXT="message1">
<ADDRESS TO="number1"></ADDRESS>
</SMS>
</MESSAGE>
The array I tried to convert is,
$TEXT="HI MANI";
$MESSAGE=array("AUTHKEY"=>"68252AGguI2SK45395d8f7",
"ROUTE"=>"4","CAMPAIGN"=>"TEST",
"SENDER"=>"OODOOP","SMS"=>array("TEXT"=>$TEXT,"ADDRESS"=>array("-TO"=>"8870300358")));
$json=array("MESSAGE"=>$MESSAGE);
$jsn=json_encode($json);
This xml output json to xml:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<MESSAGE>
<AUTHKEY>68252AGguI2SK45395d8f7</AUTHKEY>
<ROUTE>4</ROUTE>
<CAMPAIGN>TEST</CAMPAIGN>
<SENDER>OODOOP</SENDER>
<SMS>
<TEXT>HI MANI</TEXT>
<ADDRESS><-TO>8870300358
</-TO>
</ADDRESS>
</SMS>
</MESSAGE>undefined</xml>
I got wrong output, tag mistake.
Upvotes: 2
Views: 3386
Reputation: 1236
I know it is an old thread but i hope this can help anyone who seek support.
<?php
//build and array of the data you want to writ as XML
$xml_array = array ("message" => array(
"authkey"=> "68252AGguI2SK45395d8f7",
"route" => 4,
"campaign" => "test",
"sender" => "oooop",
"sms" => array (
"attribute" => "text:Hi Man",
"address" =>array (
"attribute" => "to:8870300358"
)
)
)
);
// create an XML object
$xmlobj = new SimpleXMLElement("<root></root>");
// a convert function
// this will take array in the above format and convert it in to XML Object
function convert($array, $xml){
foreach($array as $key=>$line){
if(!is_array($line)){
$data = $xml->addChild($key, $line);
}else{
$obj = $xml->addChild($key);
if(!empty($line['attribute'])){
$attr = explode(":",$line['attribute']);
$obj->addAttribute($attr[0],$attr[1]);
unset($line['attribute']);
}
convert($line, $obj);
}
}
return $xml;
}
$xmldoc =convert($xml_array,$xmlobj);
// text.xml is a blank file to write the data in it , you should create it first and give it WRITE permission
// in my case i just create it by and
print $xmldoc->asXML('test.xml');
print "<a href='test.xml'> XML file</a>";
:)
Upvotes: 1