首页 > 编程技术 > php

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

发布时间:2016-11-25 16:54

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

/*
<?xml version='1.0' encoding='utf-8' ?>
<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>

*/

<?php
$url = "http://www.111cn.net/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);

/*

*/
?>

//解析xml实例一
$objDOM = new DOMDocument();
$objDOM->load("xml.xml");
$parent = $objDOM->getElementsByTagName("Product");
foreach( $parent as $value )
  {
    $names = $value->getElementsByTagName("Name");
    $name  = $names->item(0)->nodeValue;
   
    $urls = $value->getElementsByTagName("Url");
    $url  = $urls->item(0)->nodeValue;
   
    $images = $value->getElementsByTagName("Image");
    $image  = $images->item(1)->nodeValue;
  }
 
 //DOMDocument实例二
 
$xml = new DOMDocument();
$xml->load("me.xml");
$postDom = $xml->getElementsByTagName("post");
foreach($postDom as $post){
$title = $post->getElementsByTagName("title");
echo "Id: " . $title->item(0)->attributes->item(0)->nodeValue . "<br />";
echo "Title: " . $title->item(0)->nodeValue . "<br />";
echo "Details: " . $post->getElementsByTagName("details")->item(0)->nodeValue . "<br /><br />";
}
 
?>
xml.xml
<Root>
        <Category>
                <Product>
                        <Name>网页制作教程教程</Name>
                        <Image>
                                <SizeName>Small</SizeName>
                                <Url>http://www.111cn.net</Url>
                        </Image>
                        <Image>
                                <SizeName>Medium</SizeName>
                                <Url>http://www.111cn.net</Url>
                        </Image>
                        <Image>
                                <SizeName>Large</SizeName>
                                <Url>http://www.111cn.net</Url>
                        </Image>
                </Product>
        </Category>
</Root>


me.xm;

<?xml version="1.0" encoding="utf-8"?>
<phplamp>
<post>
<title id="1">PHP XML处理介绍一</title>
<details>详细内容一</details>
</post>
<post>
<title id="2">PHP XML处理介绍二</title>
<details>详细内容二</details>
</post>
<post>
<title id="3">PHP XML处理介绍三</title>
<details>详细内容三</details>
</post>
</phplamp>

 代码如下 复制代码

//xml string
$xml_string="<?xml version='1.0'?>
<users>
<user id='398'>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id='867'>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}

json数据解析代码

 

 代码如下 复制代码

$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php


//xml string
$xml_string="<?xml version='1.0'?>
<users>
<user id='398'>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id='867'>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}

php还自带了一个PHP XML Parser
PHP XML Parser 简介
XML 函数允许我们解析 XML 文档,但无法对其进行验证。

XML 是一种用于标准结构化文档交换的数据格式。您可以在我们的 XML 教程 中找到更多有关 XML 的信息。

该扩展使用 Expat XML 解析器。

Expat 是一种基于事件的解析器,它把 XML 文档视为一系列事件。当某个事件发生时,它调用一个指定的函数处理它。

Expat 是无验证的解析器,忽略任何链接到文档的 DTD。但是,如果文档的形式不好,则会以一个错误消息结束。

由于它基于事件,且无验证,Expat 具有快速并适合 web 应用程序的特性。

XML 解析器函数允许我们创建 XML 解析器,并为 XML 事件定义句柄。

 
 */
 
 $epg_info = $_GET['epg_info'];
    $epg_info = urldecode($epg_info);
    print_r($epg_info);
    //echo $epg_info;
    //exit();

    $doc = new DOMDocument();
    $xml = file_get_contents($epg_info);     //这里是我新改过的
    $doc->loadXML($xml);
  $server_ip = $doc->getElementsByTagName("server_ip")->item(0)->nodeValue;
    $group_name = $doc->getElementsByTagName("group_name")->item(0)->nodeValue;
    $group_path = $doc->getElementsByTagName("group_path")->item(0)->nodeValue;
    $oss_user_id = $doc->getElementsByTagName("oss_user_id")->item(0)->nodeValue;
    $page_url = $doc->getElementsByTagName("page_url")->item(0)->nodeValue;
  
    echo 'server_ip:'. $server_ip.'<br>';
    echo 'group_name:'. $group_name.'<br>';
    echo 'group_path:'. $group_path.'<br>';
    echo 'oss_user_id:'. $oss_user_id.'<br>';
    echo 'page_url:'. $page_url.'<br>';

<?php

class rssGenerator_rss
{
    var $rss_version = '2.0';
    var $encoding = '';
    var $stylesheet = '';

    function cData($str)
    {
        return '<![CDATA[ ' . $str . ' ]]>';
    }

    function createFeed($channel)
    {
        $selfUrl = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http://' : 'https教程://');
        $selfUrl .= $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        $rss = '<?xml version="1.0"';
        if (!empty($this->encoding)) {
            $rss .= ' encoding="' . $this->encoding . '"';
        }
        $rss .= '?>' . " ";
        if (!empty($this->stylesheet)) {
            $rss .= $this->stylesheet . " ";
        }
        $rss .= '<!-- Generated on ' . date('r') . ' -->' . " ";
        $rss .= '<rss version="' . $this->rss_version . '" xmlns:atom="http://www.w3.org/2005/Atom">' . " ";
        $rss .= '  <channel>' . " ";
     $rss .= '    <atom:link href="' . ($channel->atomLinkHref ? $channel->atomLinkHref : $selfUrl) . '" rel="self" type="application/rss+xml" />' . " ";
        $rss .= '    <title>' . $channel->title . '</title>' . " ";
        $rss .= '    <link>' . $channel->link . '</link>' . " ";
        $rss .= '    <description>' . $channel->description . '</description>' . " ";
        if (!empty($channel->language)) {
            $rss .= '    <language>' . $channel->language . '</language>' . " ";
        }
        if (!empty($channel->copyright)) {
            $rss .= '    <copyright>' . $channel->copyright . '</copyright>' . " ";
        }
        if (!empty($channel->managingEditor)) {
            $rss .= '    <managingEditor>' . $channel->managingEditor . '</managingEditor>' . " ";
        }
        if (!empty($channel->webMaster)) {
            $rss .= '    <webMaster>' . $channel->webMaster . '</webMaster>' . " ";
        }
        if (!empty($channel->pubDate)) {
            $rss .= '    <pubDate>' . $channel->pubDate . '</pubDate>' . " ";
        }
        if (!empty($channel->lastBuildDate)) {
            $rss .= '    <lastBuildDate>' . $channel->lastBuildDate . '</lastBuildDate>' . " ";
        }
        foreach ($channel->categories as $category) {
            $rss .= '    <category';
            if (!empty($category['domain'])) {
                $rss .= ' domain="' . $category['domain'] . '"';
            }
            $rss .= '>' . $category['name'] . '</category>' . " ";
        }
        if (!empty($channel->generator)) {
            $rss .= '    <generator>' . $channel->generator . '</generator>' . " ";
        }
        if (!empty($channel->docs)) {
            $rss .= '    <docs>' . $channel->docs . '</docs>' . " ";
        }
        if (!empty($channel->ttl)) {
            $rss .= '    <ttl>' . $channel->ttl . '</ttl>' . " ";
        }
        if (sizeof($channel->skipHours)) {
            $rss .= '    <skipHours>' . " ";
            foreach ($channel->skipHours as $hour) {
                $rss .= '      <hour>' . $hour . '</hour>' . " ";
            }
            $rss .= '    </skipHours>' . " ";
        }
        if (sizeof($channel->skipDays)) {
            $rss .= '    <skipDays>' . " ";
            foreach ($channel->skipDays as $day) {
                $rss .= '      <day>' . $day . '</day>' . " ";
            }
            $rss .= '    </skipDays>' . " ";
        }
        if (!empty($channel->image)) {
            $image = $channel->image;
            $rss .= '    <image>' . " ";
            $rss .= '      <url>' . $image->url . '</url>' . " ";
            $rss .= '      <title>' . $image->title . '</title>' . " ";
            $rss .= '      <link>' . $image->link . '</link>' . " ";
            if ($image->width) {
                $rss .= '      <width>' . $image->width . '</width>' . " ";
            }
            if ($image->height) {
                $rss .= '      <height>' . $image->height . '</height>' . " ";
            }
            if (!empty($image->description)) {
                $rss .= '      <description>' . $image->description . '</description>' . " ";
            }
            $rss .= '    </image>' . " ";
        }
        if (!empty($channel->textInput)) {
            $textInput = $channel->textInput;
            $rss .= '    <textInput>' . " ";
            $rss .= '      <title>' . $textInput->title . '</title>' . " ";
            $rss .= '      <description>' . $textInput->description . '</description>' . " ";
            $rss .= '      <name>' . $textInput->name . '</name>' . " ";
            $rss .= '      <link>' . $textInput->link . '</link>' . " ";
            $rss .= '    </textInput>' . " ";
        }
        if (!empty($channel->cloud_domain) || !empty($channel->cloud_path) || !empty($channel->cloud_registerProcedure) || !empty($channel->cloud_protocol)) {
            $rss .= '    <cloud domain="' . $channel->cloud_domain . '" ';
            $rss .= 'port="' . $channel->cloud_port . '" path="' . $channel->cloud_path . '" ';
            $rss .= 'registerProcedure="' . $channel->cloud_registerProcedure . '" ';
            $rss .= 'protocol="' . $channel->cloud_protocol . '" />' . " ";
        }
        if (!empty($channel->extraXML)) {
            $rss .= $channel->extraXML . " ";
        }
        foreach ($channel->items as $item) {
            $rss .= '    <item>' . " ";
            if (!empty($item->title)) {
                $rss .= '      <title>' . $item->title . '</title>' . " ";
            }
            if (!empty($item->description)) {
                $rss .= '      <description>' . $item->description . '</description>' . " ";
            }
            if (!empty($item->link)) {
                $rss .= '      <link>' . $item->link . '</link>' . " ";
            }
            if (!empty($item->pubDate)) {
                $rss .= '      <pubDate>' . $item->pubDate . '</pubDate>' . " ";
            }
            if (!empty($item->author)) {
                $rss .= '      <author>' . $item->author . '</author>' . " ";
            }
            if (!empty($item->comments)) {
                $rss .= '      <comments>' . $item->comments . '</comments>' . " ";
            }
            if (!empty($item->guid)) {
                $rss .= '      <guid isPermaLink="';
                $rss .= ($item->guid_isPermaLink ? 'true' : 'false') . '">';
                $rss .= $item->guid . '</guid>' . " ";
            }
            if (!empty($item->source)) {
                $rss .= '      <source url="' . $item->source_url . '">';
                $rss .= $item->source . '</source>' . " ";
            }
            if (!empty($item->enclosure_url) || !empty($item->enclosure_type)) {
                $rss .= '      <enclosure url="' . $item->enclosure_url . '" ';
                $rss .= 'length="' . $item->enclosure_length . '" ';
                $rss .= 'type="' . $item->enclosure_type . '" />' . " ";
            }
            foreach ($item->categories as $category) {
                $rss .= '      <category';
                if (!empty($category['domain'])) {
                    $rss .= ' domain="' . $category['domain'] . '"';
                }
                $rss .= '>' . $category['name'] . '</category>' . " ";
            }
            $rss .= '    </item>' . " ";
        }
        $rss .= '  </channel>' . " ";
        return $rss .= '</rss>';
    }

}

class rssGenerator_channel
{
    var $atomLinkHref = '';
    var $title = '';
    var $link = '';
    var $description = '';
    var $language = '';
    var $copyright = '';
    var $managingEditor = '';
    var $webMaster = '';
    var $pubDate = '';
    var $lastBuildDate = '';
    var $categories = array();
    var $generator = '';
    var $docs = '';
    var $ttl = '';
    var $image = '';
    var $textInput = '';
    var $skipHours = array();
    var $skipDays = array();
    var $cloud_domain = '';
    var $cloud_port = '80';
    var $cloud_path = '';
    var $cloud_registerProcedure = '';
    var $cloud_protocol = '';
    var $items = array();
    var $extraXML = '';

}

class rssGenerator_image
{
    var $url = '';
    var $title = '';
    var $link = '';
    var $width = '88';
    var $height = '31';
    var $description = '';

}

class rssGenerator_textInput
{
    var $title = '';
    var $description = '';
    var $name = '';
    var $link = '';

}

class rssGenerator_item
{
    var $title = '';
    var $description = '';
    var $link = '';
    var $author = '';
    var $pubDate = '';
    var $comments = '';
    var $guid = '';
    var $guid_isPermaLink = true;
    var $source = '';
    var $source_url = '';
    var $enclosure_url = '';
    var $enclosure_length = '0';
    var $enclosure_type = '';
    var $categories = array();

}

?>

实例

<?php

require_once 'rss_generator.inc.php';

$rss_channel = new rssGenerator_channel();
$rss_channel->atomLinkHref = '';
$rss_channel->title = 'My News';
$rss_channel->link = 'http://111cn.net教程/news.php';
$rss_channel->description = 'The latest news about web-development.';
$rss_channel->language = 'en-us';
$rss_channel->generator = 'PHP RSS Feed Generator';
$rss_channel->managingEditor = 'editor@mysite.com (Alex Jefferson)';
$rss_channel->webMaster = 'webmaster@mysite.com (Vagharshak Tozalakyan)';

$item = new rssGenerator_item();
$item->title = 'New website launched';
$item->description = 'Today I finaly launch a new website.';
$item->link = 'http://111cn.net';
$item->guid = 'http://111cn.net';
$item->pubDate = 'Tue, 07 Mar 2006 00:00:01 GMT';
$rss_channel->items[] = $item;

$item = new rssGenerator_item();
$item->title = 'Another website launched';
$item->description = 'Just another website launched.';
$item->link = 'http://111cn.net';
$item->guid = 'http://111cn.net';
$item->pubDate = 'Wed, 08 Mar 2006 00:00:01 GMT';
$rss_channel->items[] = $item;

$rss_feed = new rssGenerator_rss();
$rss_feed->encoding = 'UTF-8';
$rss_feed->version = '2.0';
header('Content-Type: text/xml');
echo $rss_feed->createFeed($rss_channel);

?>

标签:[!--infotagslink--]

您可能感兴趣的文章: