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

高洛峰
Release: 2023-03-04 06:00:01
Original
1103 people have browsed it

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>
Copy after login

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;
}
Copy after login

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;
}
Copy after login

The above method json_to_xml can support aaaa< /name>, does not support aaaaa 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!


Related labels:
xml
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template