一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php读取xml列表程序

时间:2008-09-25 编辑:简简单单 来源:一聚教程网

php读了xml很方便的,我们下面用dom与php自带的xml_parser来实例吧,我们先看看wk.xml 文件, 其实这里是blogbus的rss文件哦,



 
  mikeowen
  http://mikeowen.blogbus.com
 
  by blogbus.com
  Tue, 30 Jan 2007 13:46:52 +0800
 
         http://public.blogbus.com/images/head.gif
         mikeowen
         http://mikeowen.blogbus.com
        

   vanke
   tff
   http://mikeowen.blogbus.com/logs/28560579.html
   mikeowen
   Fri, 05 Sep 2008 12:41:22 +0800
 

 
   something3
   eee
   http://mikeowen.blogbus.com/logs/23972142.html
   mikeowen
   Wed, 02 Jul 2008 12:26:40 +0800
 

 

这是我一个同事的博客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";
  }
  ?>

这种代码多一点,单效率要比上面那个高很多的.

热门栏目