教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php 数组 xml json xml相互转换的方法

php 数组 xml json xml相互转换的方法

发布时间:2015-01-07   编辑:jiaochengji.com
首先,来看array-&gt;xml。<br /> &lt;?php <br /> function array2xml($array, $tag) { function ia2xml($array) { <br /> $xml=&quot;&quot;; <br /> foreach ($array as $key=&gt;$value) {

首先,来看array->xml。
<?php
function array2xml($array, $tag) {

    function ia2xml($array) {
        $xml="";
        foreach ($array as $key=>$value) {
            if (is_array($value)) {
                $xml.="<$key>".ia2xml($value)."</$key>";
            } else {
                $xml.="<$key>".$value."</$key>";
            }
        }
        return $xml;
    }

    return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML();
?>

其次,xml->array。
方法一:
function xml2phpArray($xml,$arr){
        $iter = 0;
        foreach($xml->children() as $b){
            $a = $b->getName();
            if(!$b->children()){
                $arr[$a] = trim($b[0]);
            }else{
                $arr[$a][$iter] = array();
                $arr[$a][$iter] = xml2phpArray($b,$arr[$a][$iter]);
                $iter++;
            }
        }
        return $arr;
    }

$xml = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<a><c>ccc</c><e>eee</e></a>
</note>
XML;

print_r(xml2phpArray(simplexml_load_string ( $xml ),array()));

方法二:
function XML2Array ( $xml , $recursive = false )
{
    if ( ! $recursive )
    {
        $array = simplexml_load_string ( $xml ) ;
    }
    else
    {
        $array = $xml ;
    }
   
    $newArray = array () ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        if ( isset ( $value [ 0 ] ) )
        {
            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
        }
        else
        {
            $newArray [ $key ] = XML2Array ( $value , true ) ;
        }
    }
    return $newArray ;
}

$xml = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<a><b><c>ccc</c></b><e>eee</e></a>
</note>
XML;

print_r(XML2Array($xml));

来看json->array。
json_decode($json,true);//第二个参数为true时 即为array
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

最后,来看array->json
json_encode 数组->json
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

您可能感兴趣的文章:
php 数组 xml json xml相互转换的方法
PHP-xml & jsonp转数组的方法
PHP开发APP接口全过程(一)
php xml与json间的相互转换例子
接口返回数据用xml好还是json理解
json为什么像花儿一样红
php解析JSON中文乱码问题的解决方法
轻松实现JavaBeans到XML的相互转换
Python、PHP通过xml-rpc进行通信,xml-rpc中文的解决
XML和JSON有什么区别?

[关闭]
~ ~