php xml与json间的相互转换例子
xml转成json与json转成xml都是非常的简单了,但小编在网上找了N久没有找到,下面给各位整理一篇php xml与json间的相互转换例子,有兴趣的可进入看看.
今天在网上想找个将xml转成json的方法,找了半天没找到,找到了,根本没有什么用,有一个service_JSON说的挺像真的,找开后就一个JSON.php,php5.0以后已经把它加进来,json_decode和json_encode,想走捷径的,唉,靠人不如靠已,以下是我写的一个方法.
一,参考xml文件如下
<?xml version="1.0" encoding="UTF-8" <humans> <zhangying> <name>张映</name> <sex>男</sex> <old>28</old> </zhangying> <tank> <name>tank</name> <sex> <hao>yes</hao> <aaaa>no</aaaa> </sex> <old>28</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(emptyempty($source)){ return false; } $array = json_decode($source); //php5,以及以上,如果是更早版本,?下?JSON.php $xml ='<!--l version="1.0" encoding="'.$charset.'-->'; $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; }
上面的方法json_to_xml,可以支持
教程网址:
欢迎收藏∩_∩但请保留本文链接。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
