最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
php读取xml列表程序
时间:2008-09-25 编辑:简简单单 来源:一聚教程网
php读了xml很方便的,我们下面用dom与php自带的xml_parser来实例吧,我们先看看wk.xml 文件, 其实这里是blogbus的rss文件哦,
http://mikeowen.blogbus.com
http://mikeowen.blogbus.com
http://mikeowen.blogbus.com/logs/28560579.html
http://mikeowen.blogbus.com/logs/23972142.html
这是我一个同事的博客rss文件我取下来作实例了吧.下面我们来看看解析xml 的方法用dom来做,
$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";
}
?>
简单吧,直接读取节点然后再取当前第一个节点的值就行了.好了下面我们再看第种方法用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";
}
?>
这种代码多一点,单效率要比上面那个高很多的.
-
上一个: php把txt文本转换成数组并保存数据库
-
下一个: 如何清除网页病毒
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24