Home >Backend Development >PHP Tutorial >PHP realizes the mutual conversion function example between xml and json

PHP realizes the mutual conversion function example between xml and json

高洛峰
高洛峰Original
2016-12-22 14:44:591122browse

The example in this article describes the mutual conversion function between xml and json in php. Share it with everyone for your reference, the details are as follows:

Use php to convert between xml and json:

Please check the php manual for related functions.

1. The reference xml is as follows

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

2. Convert xml to json

Use 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;
}

3. Convert json to xml

Use recursive function

public function json_to_xml($source,$charset=&#39;utf8&#39;) {
if(empty($source)){
return false;
}
//php5,以及以上,如果是更早版本,请查看JSON.php
$array = json_decode($source);
$xml =&#39;&#39;;
$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;
}

The above method json_to_xml can support 8a11bc632ea32a57b3e3693c7987c420aaaa546fde45d380d87fb4513b2981f95ed1, does not support ae197f51c5b53feaa6a4ee5c5c11e9cfaaaaadf406f776eecbaf16b62325323196f14 You can understand it by looking at the code.


For more related articles on examples of how PHP implements the mutual conversion function between xml and json, please Follow PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn