首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将json转换为xml

将json转换为xml
EN

Stack Overflow用户
提问于 2015-05-31 18:29:22
回答 1查看 2.6K关注 0票数 1

我需要使用laravel将json格式转换为xml。我期望如下所示的输出。

代码语言:javascript
复制
   <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>

我尝试转换的数组是,

代码语言:javascript
复制
$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:

代码语言:javascript
复制
<?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>

我得到了错误的输出,标签错误。

EN

回答 1

Stack Overflow用户

发布于 2018-12-08 04:25:09

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

代码语言:javascript
复制
<?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>";

:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30556366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档