laravel json to xml



我需要使用laravel将json格式转换为xml。我希望输出如下:

   <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>

我尝试转换的数组是

$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);

这个xml输出json到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 error .

我知道这是一个旧的帖子,但我希望这能帮助任何寻求支持的人。

<?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>";

:)

最新更新