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

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

May 25, 2016 pm 04:41 PM

在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


本文地址:

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)