laravel json到xml [英] laravel json to xml

查看:85
本文介绍了laravel json到xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

我尝试转换的数组是

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

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.

推荐答案

我知道这是一个旧线程,但是我希望这可以帮助寻求支持的任何人.

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

:)

这篇关于laravel json到xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆