php domDocument分析xml文档

 更新时间:2016年11月25日 16:55  点击:1505

 
 */
 
 $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>';

 代码如下 复制代码

//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 事件定义句柄。

<?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);

?>

<?php

class rss74 {

    // RSS feed title:
    var $title = "Untitled";
   
    // RSS description:
    var $desc = "";
   
    // RSS base url
    // -> Example: http://www.jonasjohn.de/
    var $base_url = "";
   
    // XSL file for the resulting RSS feed:
    var $xsl_file = 'rss.xsl';
   
    // RSS 2.0 Specification (URL):
    var $doc_url = 'http://blogs.law.harvard.edu/tech/rss';
   
    // Copyright text:
    // -> Example: Copyright 2006, Jonas John
    var $copyright = '';
   
    // RSS language setting:
    // Example: en-us, de-de, fr-fr
    var $language = 'en-us';
   
    // Managing editor and webmaster:
    // (should contain a E-Mail adress)
    var $managing_editor = '';
    var $webmaster = '';
   
    // Feedburner URL
    // Example: http://feeds.feedburner.com/codedump-rss
    // (If a FB URL is set, all requests except the Feedburner and Google
    // requests will be redricted to the feedburner URL)
    var $feedburner_url = '';
   
    // RSS generator:
    var $generator = 'rss74/v0.3';
   
    // Limit RSS entries to:
    // (Example: 20, 30, 40, 50, etc.)
    var $limit_entries = 20;

    // RSS items:
    var $items = array();

    // constructor:
    function rss74(){
    }  
   
    function add_entry($entry){   
   
        // create date key:
        $date = isset($entry['date']) ? $entry['date'] : time();  

        // add unique string:
        $date .= '_' . md5($entry['title']);
       
        $this->items[$date] = $entry;
    }
   
    function _get_val(&$array, $key){
        return isset($array[$key]) ? $array[$key] : '';
    }
   
    function _exists_val(&$array, $key){
        return isset($array[$key]);
    }
   
    function get_rss_headers($rss_webpath){
        return '<link rel="alternate" type="application/rss+xml" title="RSS" href="'.$rss_webpath.'" />';
    }
   
    function print_rss(){
        global $_SERVER;
   
        krsort($this->items);
        $this->items = array_slice($this->items, 0, $this->limit_entries);
       
        $first_item = array_keys($this->items);
        $first_item = $first_item[0];
       
        $last_change = $this->items[$first_item]['date'];
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_change).' GMT');
       
        header('Content-Type: text/xml; charset=utf-8');

        if (!empty($this->feedburner_url)){
            if (!preg_match("/feedburner/i", $_SERVER['HTTP_USER_AGENT']) and !preg_match("/google/i", $_SERVER['HTTP_USER_AGENT'])) {
                header('HTTP/1.1 301 Moved Permanently');
                header('Location: ' . $this->feedburner_url);
                print '<a href="'.$this->feedburner_url.'">Redirecting...</a>';
                return true;
            }
        }

        print '<?xml version="1.0" encoding="utf-8"?>' . " ";
       
        if ($this->xsl_file != '')
            print '<?xml-stylesheet href="rss.xsl" type="text/xsl" media="screen"?>' . " ";
       
        print '<!DOCTYPE rss [<!ENTITY % HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent">]>' . " ";
       
        print "<!-- Hello! This web page is a RSS file that is meant to be read by a RSS reader application. Look at http://en.wikipedia.org/wiki/RSS to learn more about RSS. -->";
       
        print '<rss version="2.0" xmlns:xhtml="http://www.w3.org/1999/xhtml">' . " ";
        print '<channel>' . " ";
       
        print " ".'<title>'.htmlentities($this->title).'</title>' . " ";
       
        if (!empty($this->desc))
            print " ".'<description>'.htmlentities($this->desc).'</description>' . " ";
       
        if (!empty($this->base_url))
            print " ".'<link>'.htmlentities($this->base_url).'</link>' . " ";
       
        print " ".'<lastBuildDate>'.date('r', time()).'</lastBuildDate>' . " ";
        print " ".'<pubDate>'.date('r', time()).'</pubDate>' . " ";
       
        if (!empty($this->generator))
            print " ".'<generator>'.$this->generator.'</generator>' . " ";
       
        if (!empty($this->copyright))
            print " ".'<copyright>'.$this->copyright.'</copyright>' . " ";
           
        if (!empty($this->doc_url))
            print " ".'<docs>'.$this->doc_url.'</docs>' . " ";
       
        if (!empty($this->language))
            print " <language>".$this->language."</language> ";
           
        if (!empty($this->managing_editor))
            print " <managingEditor>".$this->managing_editor."</managingEditor> ";

        if (!empty($this->webmaster))
            print " <webMaster>".$this->webmaster."</webMaster> ";


        while(list($num, $item) = each($this->items)){
     
            print " <item> ";
            print " <title>".htmlentities($this->_get_val($item, 'title'))."</title> ";
           
            if ($this->_exists_val($item, 'url')){
                print " <link>".$this->_get_val($item, 'url')."</link> ";
                print " <guid isPermaLink="true">".$this->_get_val($item, 'url')."</guid> ";
            }
           
            if ($this->_exists_val($item, 'desc'))
                print " <description><![CDATA[".$this->_get_val($item, 'desc')."]]></description> ";
           
            if ($this->_exists_val($item, 'date')){
                print " <pubDate>".date('r', intval($this->_get_val($item, 'date')))."</pubDate> ";
            }
       
            $cats = array();
            while(list($cn, $citem) = each($cats)){
                print " <category>$citem</category> ";
            }
               
            print " </item> ";
            
        }

        print " </channel> ";
        print "</rss>";
       
        return true;
       
    }
}

实例

 include('inc.rss74.php');

    // RSS items list:
    $example_list = array();   
       
    /*
    ** Create some test entries:
    */
   
    $m = rand(8, 30);
    for ($x = 0; $x < $m; $x++){
   
        // create a random UNIX-Timestamp:
        $date = rand(1166000000, 1166400000);
   
        $example_list[] = array(
            'title' => 'Example RSS message #' . $x,
            'url' => 'http://www.jonasjohn.de/#' . $x,
            'desc' => 'This is a example message from RSS74!',
            'date' => $date
        );
   
    }
   
   
    // create new RSS object:
    $rss = new rss74();
   
    /*
    ** Set RSS informations:
    */
   
    // RSS title:
    $rss->title = 'RSS example 2';
   
    // RSS description:
    $rss->desc = 'This feed shows some random entries.';
   
    // base URL of your homepage:
    $rss->base_url = 'http://www.example.org/';
   
    // limit entry count to 20
    $rss->limit_entries = 20;
   
    // RSS Editor
    $rss->managing_editor = 'Yourname <yourname@example.org>';

    // Webmaster name
    $rss->webmaster = 'Yourname <yourname@example.org>';
   
    // language:
    $rss->language = 'en-us';
   
    // Copyright message:
    $rss->copyright = 'Copyright 2006, Yourname';
   
    // Set Feedburner adress:
    //$rss->feedburner_url = 'http://feeds.feedburner.com/codedump-rss';
    // (empty) = No redirection

    // Set "xsl_file" to empty to disable the XSL file:
    $rss->xsl_file = '';

    // Add entries to the RSS object:
    while (list($date, $entry) = each($example_list)){
              
        $rss->add_entry(array(
            'title'     => $entry['title'],
            'url'       => $entry['url'],
            'desc'      => $entry['desc'],
            'date'      => $entry['date']
        ));
   
    }
   
    // let rss74 do the rest:
    $rss->print_rss();

?>

 

<?
class arrayTree
{
 private $stack;
 private $tree;
 private $location;
 private $locationstring;
 
 
 public function __construct($tree = false)
 { $this->stack = array();
  if ($tree)
   $this->tree = $tree;
  else
   $this->tree = array();
   
  $this->location = 0;
 }
 
 public  function startBranch()
 { $this->location++;
  $this->stack[] = $this->location;
  $this->location = 0;
  $this->nodes = 0;
  $this->locationstring = "";
  foreach($this->stack as $v)
   $this->locationstring .="['node:$v']";

  eval('$this->tree'."$this->locationstring = array(); ");
  eval('$this->tree'."$this->locationstring"."['nodes'] = 0; ");

 }
 public  function addLeaf($name, $value)
 { $name = htmlspecialchars($name, ENT_QUOTES); 
  if (is_array($value) && sizeof($value)> 0)   
  { $arr = "array( ";
   foreach($value as $n=>$v)
   { $v = addslashes("$v");
    $arr .= "'$n' => '$v',";
   }
   $arr .= "'$n' => '$v')";
   //echo '$this->tree'."$this->locationstring"."['$name']"." = $arr; ";
   eval ('$this->tree'."$this->locationstring"."['$name']"." = $arr; ");

  }
  else
  {
   if (is_array($value) && sizeof($value)== 0)
    $value = '';
 
   $value = htmlspecialchars($value, ENT_QUOTES);
   $tmp = '$this->tree'."$this->locationstring"."['$name']".' = "$value";'." ";
   //echo ($tmp);
   eval($tmp);
  }  
 }
 public  function endBranch()
 { 
  $this->location = array_pop($this->stack);
  $this->locationstring = "";
  foreach($this->stack as $v)
   $this->locationstring .= "['node:$v']";

  eval('$this->tree'."$this->locationstring"."['nodes'] = $this->location; ");   
 }
 public function gettree()
 { return $this->tree;
 }
}


/***************************************************
**  XMLParser Object
**  Helper object for parsing XML into an arrayTree
***************************************************/
 
class XMLParser

 private $filename;
 private $data;
 private $currentItem;
 private $didread;
 private $depth;
 private $deptharr;
 private $parsed;
 private $pointer;
 private $parser;
 private $p;
 private $arrayout;
 private $tree;
 
 
 public  function __construct($xml, $isfile = true)
 { 
  if ($isfile)
  { $file = $xml;
   $this->filename = $file;
  }
  else
  { $this->data = $xml;
   $this->filename = false;
  }
   
  $this->tree = new arrayTree;
  $this->tree->addLeaf('nodes', 0);
    $this->depth = 0;
  $this->deptharr = array();
  $this->pointer = '$this->parsed';
  $this->currentItem = array();
  $this->didread = false; 
  $this->parsed = array();
  $this->arrayout = "";
 }  
 
 public  function startElement($parser, $name, $attrs)
 { $this->parsed = "";
  $this->tree->startBranch();
  $this->tree->addLeaf('name', $name);
  $this->tree->addLeaf('attributes', $attrs);
 }
 public  function characterData($parser, $data)
 { if (!$this->didread)
   $this->parsed  = $data;
  else
   $this->parsed .= $data;
  $this->didread = true;
 }
 public function endElement($parser, $name)
 { $this->tree->addLeaf('value',$this->parsed);
  $this->parsed = "";
  $this->tree->endBranch(); 
 }
 public function parse()
 { 
  
  $this->parser = xml_parser_create();
  xml_set_object($this->parser, $this);
  xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
  xml_set_element_handler($this->parser, "startElement", "endElement");
  xml_set_character_data_handler($this->parser, "characterData");
  
  if ($this->filename !== false)
  { $data = file_get_contents($this->filename);
   if (!$data)
    return false;
  }
  else
   $data = $this->data;

     $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
       $data=str_replace("&","&amp;",$data);
     if (!xml_parse($this->parser, $data))
     {   die(sprintf("XML error: %s at line %d",
            xml_error_string(xml_get_error_code($this->parser)),
               xml_get_current_line_number($this->parser)));
     }
  xml_parser_free($this->parser);
  $data=str_replace("&amp;","&",$this->tree->gettree());
  return $data['node:1'];
 }
 
 
}


/***************************************************
**  swiftXML Object
**  Allows user access to XML data stored in tree
***************************************************/

class swiftXML implements IteratorAggregate
{
 private $XMLtree;
 
 public function __construct(&$xml = false, $type = XML_FILE)
 {
  if (is_array($xml) || $type == XML_TREE)
  {  $this->usearray($xml);
  }
  else if ($type == XML_FILE)
  { $this->usefile($xml);
   
  }
  else if ($type == XML_TEXT)
  { $this->usetext($xml);
  }
  
 }

 public function & __get($x)
 {
  return $this->get($x); 
 }
 
 public function __set($x,$y)
 { 
  $this->set($x,$y);

 }
 public function __call($x, $y)
 { if (array_key_exists($x,$this->XMLtree))
   return $this->XMLtree[$x];
  else
   return false;
 }
 
 public function __toString()
 {
  return $this->XMLtree['value'];
 }
 // Iterator function
 public function getIterator()
 {   return new ArrayIterator($this->XMLtree);
    }
 
 // initialize functions
 public function usefile($file)
 { $x = new XMLParser($file);
  $this->XMLtree = $x->parse();
 }

 public function usetext($text)
 { $x = new XMLParser($text,false);
  $this->XMLtree = $x->parse();
 }
 public function usearray(&$arr)
 { $this->XMLtree = $arr;
 }
 
 
 // return Tree as XML
 public function asXML($header = true, $tree = false, $depth = 0)
 { if (!$tree)
   $tree = $this->XMLtree;
  $output = "";
  if ($header)
  { 
   $output = "<?xml version="1.0" encoding="UTF-8" ?> ";
  }
 
  $tabs = str_repeat (" ",$depth);
  $output .= "$tabs<$tree[name]";
  if ($tree['attributes'] != "" && is_array($tree['attributes']))
  { foreach ($tree['attributes'] as $n => $v)
     $output .= " $n="$v"";
  }
  $output .= ">$tree[value]";
  
  if ($tree['nodes'] > 0)
  { foreach ($tree as $n => $v)
   { if (substr($n,0,5) == "node:")
     $output .= " " . $this->asXML(false,$tree[$n],$depth+1);
   } 
   $output .=" $tabs"; 
  
  }
  $output .="</$tree[name]>";
  return $output;
 }
 
 // return XMLtree
 public function getDetailedTree()
 { return $this->XMLtree;
 }
 
 // return a simplified tree as an array, where the array keys correspond to XML tags
 public function getSimpleTree($showattribs = false, &$tree = false)
 { if (!$tree)
   $tree = $this->XMLtree;
  // tree has no branches
  if (sizeof($tree) < 5)
   return $tree['value'];
 
  $output = array();
  foreach($tree as $n=>$v)
  {  if(substr($n,0,5) == 'node:')
   { $vname = $v['name'];
    $attribstr = "";
    $vattrib = $v['attributes'];
    if (array_key_exists($vname, $output))
    { if (!is_array($output[$vname]) || !array_key_exists(0,$output[$vname]))
     { $existingvalue = $output[$vname];
      $existingvattrib = false;
      if ($showattribs && array_key_exists($vname."/attributes",$output))
       $existingvattrib = $output[$vname."/attributes"];
      $output = array();
      $output[$vname] = array();     
      $output[$vname][] = $existingvalue;
     
      if ($showattribs  && $existingvattrib)
       $output[$vname]["0/attributes"] = $existingvattrib;
     }
     $output[$vname][] = $this->getSimpleTree($showattribs,$v);
     if ($showattribs && is_array($vattrib))
      $output[$vname][end(array_keys($output[$vname]))."/attributes"] = $vattrib;
    }
    else
    { 
     $output[$vname] = $this->getSimpleTree($showattribs, $v);  
     //echo "-->$vname:".$output[$vname]." ";
     if ($showattribs && is_array($vattrib))
      $output[$vname."/attributes"]= $vattrib;
    }
   }
  }
  return $output;
 } 

 // $location takes the format "block1/block2/block3"
 private function & getNodeByLocation($location, &$tree= false)
 { if (!$tree)
   $tree = &$this->XMLtree;

   
  
  $location = ereg_replace("^/", "",$location);
  $location = ereg_replace("/$", "",$location);


  if ($slashpos = strpos($location,"/"))
  { $nodename = substr($location,0,$slashpos);
   $rest = substr($location,$slashpos+1,strlen($location)-$slashpos+1);
   return $this->getNodeByLocation($rest,$this->getNodebyName($tree, $nodename));
  }
  else
   return $this->getNodeByName($tree, $location);
 }
 
 public function doesExist($location)
 { return getNodeByLocation($location) ==! false ? true : false;
 }
 
 // returns XML object
 public function & getNode($location)
 { $tmp = $this->getNodeByLocation($location);
  if ($tmp === false)
   return false;
  else
   return new swiftXML($tmp,XML_TREE);
 }
 
 // accepts $newnode as XML object
 public function setNode($newnode, $location)
 { $locnode = &$this->getNodeByLocation($location);
  //print_r($locnode);
  
  $locnode = $newnode->getDetailedTree();
 }
 public function getValue($location)
 { 
  $arr = $this->getNodeByLocation($location);
  if ($arr !== false)
   return $arr['value'];
  else
   return false;
 }
 
 public function setValue($value, $location = false)
 { 
  if (!$location)
   $arr = &$this->XMLtree;
  else
   $arr = &$this->getNodeByLocation($location);
  
  $arr['value'] = $value;
  

 }
 public function set($location,$value)
 {
  
  if (is_array($value))
   $this->setTree($value,$location);
  else if (is_a($value, "swiftXML"))
   $this->setNode($value,$location);
  else
   $this->setValue($value,$location);
   
 }
 
 public function setTree($value, $location= false)
 { if (!$location)
   $arr = &$this->XMLtree;
  else 
   $arr = &$this->getNodeByLocation($location);
   
  
  $arr = $value;
 }
 
 public function getAttributes($location)
 { 
  $arr = $this->getNodeByLocation($location);
  return $arr['attributes'];
 }
 
 public function getAttribute($location, $attrib)
 { 
  $arr = $this->getNodeByLocation($location);
  if (array_key_exists($attrib, $arr['attributes']))
   return $arr['attributes'][$attrib];
  else
   return false;
 }
 
 public function setAttribute($attribname, $attribvalue, $location = false)
 { if (!$location)
   $arr = &$this->XMLtree;
  else
   $arr = &$this->getNodeByLocation($location);

  if (!is_array($arr['attributes']))
   $arr['attributes'] = array();
   
  $arr['attributes'][$attribname] = $attribvalue;
 }
 
 public function setAttributes($arr, $location = false)
 { if (!$location)
   $arr2 = &$this->XMLtree;
  else
   $arr2 = &$this->getNodeByLocation($location);

  $arr2['attributes'] = $arr;
  
 }
 
 // Easiest way to get info from an XML document is to use function get()
 // get() guesses what format you'd like the data in based on the data. 
 // It will return an array of XML objects if $location is ambiguous. 
 // If one tag exists at $location, it will be returned and an XML object, unless it has no attributes,
 // in which case the value be returned as a string.
 //
 // Use the prefix // to indicate a location wildcard (run getNodeArrayRecursize)
 public function get($location)
 { 
  if (ereg("^//",$location) || ereg("^*/",$location))
   return $this->getNodeArrayRecursive(substr($location,2,strlen($location)-2));
 
   
  $output = $this->getNodeArray($location);
  
  
  if ($output !== false && count($output) == 1)
  { $tree = $output[0]->getDetailedTree();
   if ($tree['nodes'] == 0 && !is_array($tree['attributes']))
    $output = $tree['value'];
   else
    $output = $output[0];
  }
  return $output;   
 }
 
 public function getNodeArray($location)
 { 
     if (ereg("^//",$location) || ereg("^*/",$location))
   return $this->getNodeArrayRecursive(substr($location,2,strlen($location)-2));
  
  $output = array();
  $lastpos = strrpos($location, "/");
  if ($lastpos !== false)
  { $subloc = substr($location,0,$lastpos);
   $nodename = substr($location,$lastpos+1,strlen($location)-1); 
   $node = $this->getNode($subloc);

   if ($node === false)
    return false;
    
   $tree = $node->getDetailedTree();
  
  }
  else
  { $subloc = $location;
   $nodename = $location;
   $tree = $this->XMLtree;
  }
    
  for ($i = 1; $i <= $tree['nodes']; $i++)
  { if ($tree["node:$i"]['name'] == $nodename)
    $output[] = swiftXML_use_tree($tree["node:$i"]);
  }
  if (count($output) == 0)
   return false;
  else
   return $output;
  
 }
 
 // returns an array of any node named $location in $tree
 private function getNodeArrayRecursive($location, $tree = false)
 { if (!$tree)
   $tree = $this->XMLtree;
   
  $output = array();
  if ($tree['name'] == $location)
   $output[] = swiftXML_use_tree($tree);
  
  for ($i = 1; $i <= $tree['nodes']; $i++)
   $output =array_merge($output, $this->getNodeArrayRecursive($location,$tree["node:$i"]));
  
  return $output; 
 }
 
 // assistant function; pulls a Subarray from the $tree
 private  function & getNodeByName(&$tree, $name, $debug = false)
 { if ($debug) echo "getNodeByName($tree,$name); ";
  if (!is_array($tree))
  { if ($debug) echo ("[".$tree."]");
   return false;
  }
  
  foreach ($tree as $n => $v)
  { if (is_array($v) and array_key_exists('name',$v))
   { if ($debug) echo $tree[$n]['name'] ." == $name ? ";
    if ($v['name'] == $name)
     return $tree[$n];    
   }
   if ($debug) echo $n." ";
  }
  return false;
 }
 
 
 public function createChild($name, $value = "", $attributes = "")
 { 
  $nodes = ++$this->XMLtree['nodes'];
  if (is_a($name, "swiftXML"))
  { $this->XMLtree["node:$nodes"] = $name->getDetailedTree();
   $nodes = $this->XMLtree['nodes'];
  }
  else
   $this->XMLtree["node:$nodes"] = array( "name" => $name,
             "value" => $value,
             "attributes" => $attributes,
             "nodes" => 0);
  return $nodes;
 } 
 
}

define("XML_FILE","file");
define("XML_TREE","tree");
define("XML_TEXT","text");
define("XML_NO_CURL",false);
 
// assistant functions for initializing XML objects
function & swiftXML_use_file($filename, $use_curl = true)

 if (ereg("://",$filename) && $use_curl && function_exists('curl_init'))
  return swiftXML_use_curl($filename);
 else
  return new swiftXML($filename, XML_FILE);
}

function & swiftXML_use_text($text)
{ return new swiftXML($text, XML_TEXT);
}


function & swiftXML_use_tree($tree)
{ return new swiftXML($tree, XML_TREE);
}

function & swiftXML_use_curl($filename)
{
 $ch = curl_init();

 curl_setopt($ch, CURLOPT_URL, $filename);
 curl_setopt($ch, CURLOPT_USERAGENT, "swiftXML/1.1");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 
 $text = curl_exec($ch);
 
 curl_close($ch);
 
 return new swiftXML($text, XML_TEXT);
}

function & swiftXML_create($name, $value = "", $attributes = "")
{
 return swiftXML_use_tree(array( "name" => $name,
         "value" => $value,
         "attributes" => $attributes,
           "nodes" => 0));
 

}
?>
分析xml文档
<html>
<body>
<?
include_once('swiftxml.1.1.php教程');

$XML= swiftXML_use_file('http://www.111cn.net教程/feed/rss2/');


echo "<h1>".$XML->get("/channel/title")."</h1>";
echo "<h2>".$XML->get("/channel/description")."</h2>";

foreach ($XML->get("//item") as $item)
{ $url   = $item->get("link");
 $title = $item->get("title");
 $desc  = $item->get("description");

 echo html_entity_decode("<h3><a href="$url">$title</a></h3><p>$desc</p> ");

}

?>
</body>
</html>

下创建 xml 文档
<?
include_once('swiftxml.1.1.php');

$rss = swiftXML_create("rss");
$rss->setAttribute("version", "2.0");

$channel = swiftXML_create("channel");
$channel->createChild("title","Swiftly Tilting");
$channel->createChild("link","http://www.111cn.net");

for($i = 0; $i < 10; $i++)
{ $item = swiftXML_create("item");
 $item->createChild("title","title $i");
 $item->createChild("description","description $i");
 $channel->createChild($item);
}

$rss->createChild($channel);

header("Content-type: text/xml");
echo $rss->asXML();

?>

[!--infotagslink--]

相关文章

  • 用js的document.write输出的广告无阻塞加载的方法

    一、广告代码分析很多第三方的广告系统都是使用document.write来加载广告,如下面的一个javascript的广告链接。复制代码 代码如下:<script type="text/javascript" src="http://gg.5173.com/adpolestar/5173/;ap=2EBE5...2014-06-07
  • MYSQL事务回滚的2个问题分析

    因此,正确的原子操作是真正被执行过的。是物理执行。在当前事务中确实能看到插入的记录。最后只不过删除了。但是AUTO_INCREMENT不会应删除而改变值。1、为什么auto_increament没有回滚?因为innodb的auto_increament的...2014-05-31
  • Mysql索引会失效的几种情况分析

    索引并不是时时都会生效的,比如以下几种情况,将导致索引失效: 1.如果条件中有or,即使其中有条件带索引也不会使用(这也是为什么尽量少用or的原因)  注意:要想使用or,又想让索引生效,只能将or条件中的每个列都加上索引 ...2014-06-07
  • python 爬取京东指定商品评论并进行情感分析

    本文主要讲述了利用Python网络爬虫对指定京东商城中指定商品下的用户评论进行爬取,对数据预处理操作后进行文本情感分析,感兴趣的朋友可以了解下...2021-05-28
  • Underscore源码分析

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。这篇文章主要介绍了underscore源码分析相关知识,感兴趣的朋友一起学习吧...2016-01-02
  • Google会不会取消PR的理由分析

    Google是这样介绍PageRank的:   Google 出类拔萃的地方在于专注开发“完美的搜索引擎”,联合创始人拉里&middot;佩奇将这种搜索引擎定义为可“确解用户...2017-07-06
  • Fatal error: Cannot redeclare class 原因分析与解决办法

    我使用的都是php __autoload状态自动加载类的,今天好好的程序不知道怎么在运行时提示Fatal error: Cannot redeclare class 了,看是重复定义了类,下面我来分析一下解决办...2016-11-25
  • 详解Document.Cookie

    这篇文章主要介绍了详解Document.Cookie的相关资料,需要的朋友可以参考下...2015-12-27
  • 简单入门级php 生成xml文档代码

    $doc = new domdocument('1.0'); // we want a nice output $doc->formatoutput = true; 代码如下 复制代码 $root = $doc->createelement('bo...2016-11-25
  • 关于PHP文件包含一些漏洞分析

    文章简单的分析了在php文件包含时inlcude的一个漏洞分析,下面希望对大家有点用处哦。 基本的文件包含漏洞: 代码如下 复制代码 <?php include...2016-11-25
  • www.111cn.net 排名大跌分析降权原因

    我的主题爱这个站以前排名非常好,后来由于自己操作不当至今还没恢复到以后的那种好的排名,希望各位站长吸取点教训哦。 下面以我们http://www.111cn.net 为例吧,做SE...2016-10-10
  • php echo print print_r三者区别分析

    php教程 echo print print_r三者区别分析 echo是PHP语句, print和print_r是函数,语句没有返回值,函数可以有返回值(即便没有用) print() 只能打印出简单类型变量的...2016-11-25
  • PHP静态分析与跨站脚本检测

    最近在看PHP静态分析与跨站脚本检测的东西,用的是维也纳大学一个博士生做出来的Pixy,这个东西是开源的,而且也作了好几年了,功能逐渐增强。现在这个3.0.3版本里...2016-11-25
  • 关于web注册页的可用性分析

      在Nielsen的可用性工程里提到可用性的其中一个原则是Errors,记得刚开博客的时候也穷举了一些关于可用性方面的文章,里面将这个errors翻译成了“少错”,实际上...2016-09-20
  • PHP session并发及session读写锁分析

    关于PHP session并发及session读写锁问题估计各大程序员都不会想到这个问题,因为一般情况我们不会使用session来做并发操作了,但有时也有可能用到,下面整理一个session并...2016-11-25
  • 最短的IE判断var ie=!-[1,]分析

    以前最短的IE判定借助于IE不支持垂直制表符的特性搞出来的。 复制代码 代码如下: var ie = !+"/v1"; 仅仅需要7bytes!参见这篇文章,《32 bytes, ehr ... 9, ehr ... 7!!! to know if your browser is IE》,讲述外国人是...2014-05-31
  • Java org.w3c.dom.Document 类方法引用报错

    这篇文章主要介绍了Java org.w3c.dom.Document 类方法引用报错的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-07
  • 深入分析PHP const与define使用区别

    const是用于类成员常量的定义了,定义之后不可改,而define我们定义的是全局常量了, 这样我们在其它地方访问但不能改变了,具体还有一些细节我们下面给各位列出来吧 注...2016-11-25
  • XmlDocument 创新对象时, 产生 xmlns="" 的解决方案

    今天做开发时碰到的XmlDocument 创新对象时, 产生 xmlns=\"\" 的,经过分析总结了问题所在,有需要朋友参考一下,可能能帮助你解决这个问题。 1. 读取时,应该添加N...2016-11-25
  • php使用dom解析含有中文字符xml文档

    一般我们直接使用dom来处理xml文档时如果里面有中文就会把中文转换成乱码了,下面我们通过使用iconv()函数实现编码转换,防止中文乱码. 代码如下 复制代...2016-11-25