Home > php教程 > php手册 > php把读取xml文档并转换成json数据代码

php把读取xml文档并转换成json数据代码

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-25 16:41:57
Original
1184 people have browsed it

在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了.

XML文档代码如下:

<?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39;   
    <root cityid="0" classid="0" placeid="0" yy="0" mm="0" pg="1" ps教程="20" maxPage="1" num="1" serverIP="58.57.65.195"> 
<expo ID="3889" cityid="53" city="北京" classid="0" classname="建筑/装潢/五金" place="中国国际展览中心" placeid="0" tm1="2010-6-3" tm2="2010-6-5" title="20会" Address="北 
里河路13号"> 
<![CDATA[2010北京第十五届中件系列]]> 
</expo> 
</root>
Copy after login

php把读取 xml 文档并转换成json数据代码如下:

<?php 
$url = "http://www.phprm.com/xml.xml"; 
$dom = new DOMDocument(); 
$dom->load($url); 
$root = $dom->documentElement; 
$arr=array(); 
foreach ($root->childNodes as $item) 
{ 
    if($item->hasChildNodes()) 
    { 
        $tmp=array(); 
        foreach($item->childNodes as $one) 
        { 
            $tmp[$one->tagName]=$one->nodeValue; 
        } 
         
        $arr[$item->tagName]=$tmp; 
    } 
} 
 
$jsonStr = json_encode($arr); 
 
var_dump($jsonStr);
Copy after login


本文地址:

转载随意,但请附上文章地址:-)

Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template