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='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; }
The above method json_to_xml can support
For more related articles on examples of how PHP implements the mutual conversion function between xml and json, please Follow PHP Chinese website!