利用php怎么对xml与json进行转换

今天就跟大家聊聊有关利用php怎么对xml与json进行转换,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、参考xml如下

<?xml version="1.0" encoding="UTF-8"?>
<humans>
<zhangying>
<name>张三</name>
<sex>男</sex>
<old>26</old>
</zhangying>
<tank>
<name>tank</name>
<sex>
<hao>yes</hao>
<aaaa>no</aaaa>
</sex>
<old>26</old>
</tank>
</humans>

二、xml转换成json

利用simplexml

public function xml_to_json($source) {
if(is_file($source)){ //传的是文件,还是xml的string的判断
$xml_array=simplexml_load_file($source);
}else{
$xml_array=simplexml_load_string($source);
}
$json = json_encode($xml_array); //php5,以及以上,如果是更早版本,请查看JSON.php
return $json;
}

三、json转换成xml

利用递归函数

public function json_to_xml($source,$charset='utf8') {
if(empty($source)){
return false;
}
//php5,以及以上,如果是更早版本,请查看JSON.php
$array = json_decode($source);
$xml ='';
$xml .= $this->change($array);
return $xml;
}
public function change($source) {
$string="";
foreach($source as $k=>$v){
$string .="<".$k.">";
//判断是否是数组,或者,对像
if(is_array($v) || is_object($v)){
//是数组或者对像就的递归调用
$string .= $this->change($v);
}else{
//取得标签数据
$string .=$v;
}
$string .="";
}
return $string;
}

看完上述内容,你们对利用php怎么对xml与json进行转换有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。