php读取xml列表程序
php读了xml很方便的,我们下面用dom与php自带的xml_parser来实例吧,我们先看看wk.xml 文件,其实这里是blogbus的rss文件,代码如下:
<?xml version="1.0" encoding="gb2312" <rss version="2.0"> <channel> <title>mikeowen</title> <link>http://mikeowen.blogbus.com</link> <description><![CDATA[Design]]></description> <generator> by blogbus.com </generator> <lastBuildDate>Tue, 30 Jan 2007 13:46:52 +0800</lastBuildDate> <image> <url>http://public.blogbus.com/images/head.gif</url> <title>mikeowen</title> <link>http://mikeowen.blogbus.com</link> </image> <item> <title>vanke</title> <description>tff</description> <link>http://mikeowen.blogbus.com/logs/28560579.html</link> <author>mikeowen</author> <pubDate>Fri, 05 Sep 2008 12:41:22 +0800</pubDate> </item> <item> <title>something3</title> <description>eee</description> <link>http://mikeowen.blogbus.com/logs/23972142.html</link> <author>mikeowen</author> <pubDate>Wed, 02 Jul 2008 12:26:40 +0800</pubDate> </item> </channel> </rss>
这是我一个同事的博客rss文件我取下来作实例了吧,下面我们来看看解析xml的方法用dom来做,实例代码如下:
<?php
$doc = new DOMDocument();
$doc->load( 'wk.xml' );
$books = $doc->getElementsByTagName( "item" );
foreach( $books as $book )
{
$authors = $book->getElementsByTagName( "title" );
$author = $authors->item(0)->nodeValue;
$publishers = $book->getElementsByTagName( "link" );
$publisher = $publishers->item(0)->nodeValue;
$titles = $book->getElementsByTagName( "pubDate" );
$title = $titles->item(0)->nodeValue;
echo "$title - $author - $publishern";
}
//开源代码phprm.com
简单吧,直接读取节点然后再取当前第一个节点的值就行了,好了下面我们再看看一种方法用php自然的,代码如下:
<?php
$g_books = array();
$g_elem = null;
function startElement( $parser, $name, $attrs )
{
global $g_books, $g_elem;
if ( $name == 'item' ) $g_books []= array();
$g_elem = $name;
}
function endElement( $parser, $name )
{
global $g_elem;
$g_elem = null;
}
function textData( $parser, $text )
{
global $g_books, $g_elem;
if ( $g_elem == 'link' ||
$g_elem == 'pubDate' ||
$g_elem == 'title' )
{
$g_books[ count( $g_books ) - 1 ][ $g_elem ] = $text;
}
}
$parser = xml_parser_create();
xml_set_element_handler( $parser, "startElement", "endElement" );
xml_set_character_data_handler( $parser, "textData" );
$f = fopen( 'wk.xml', 'r' );
while( $data = fread( $f, 4096 ) )
{
xml_parse( $parser, $data );
}
xml_parser_free( $parser );
foreach( $g_books as $book )
{
echo $book['title']." - ".$book['link']." - ";
echo $book['pubDate']."n";
}
这种代码多一点,单效率要比上面那个高很多的.
文章链接:http://www.phprm.com/develop/fs4569.html
随便收藏,请保留本文地址!