首页 > 开发 > PHP > 正文

PHP读取XML格式文件的方法总结

2024-05-04 22:48:57
字体:
来源:转载
供稿:网友

本文实例总结了PHP读取XML格式文件的方法。分享给大家供大家参考,具体如下:

books.xml文件:

<books><book><author>Jack Herrington</author><title>PHP Hacks</title><publisher>O'Reilly</publisher></book><book><author>Jack Herrington</author><title>Podcasting Hacks</title><publisher>O'Reilly</publisher></book></books>

1.DOMDocument方法

<?php$doc = new DOMDocument();$doc->load( 'books.xml' );$books = $doc->getElementsByTagName( "book" );foreach( $books as $book ){$authors = $book->getElementsByTagName( "author" );$author = $authors->item(0)->nodeValue;$publishers = $book->getElementsByTagName( "publisher" );$publisher = $publishers->item(0)->nodeValue;$titles = $book->getElementsByTagName( "title" );$title = $titles->item(0)->nodeValue;echo "$title - $author - $publisher/n";echo "<br>";}?>

2.用 SAX 解析器读取 XML:

<?php$g_books = array();$g_elem = null;function startElement( $parser, $name, $attrs ) {global $g_books, $g_elem;if ( $name == 'BOOK' ) $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 == 'AUTHOR' ||$g_elem == 'PUBLISHER' ||$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( 'books.xml', 'r' );while( $data = fread( $f, 4096 ) ){xml_parse( $parser, $data );}xml_parser_free( $parser );foreach( $g_books as $book ){echo $book['TITLE']." - ".$book['AUTHOR']." - ";echo $book['PUBLISHER']."/n";}?>

3.用正则表达式解析 XML:

<?php$xml = "";$f = fopen( 'books.xml', 'r' );while( $data = fread( $f, 4096 ) ) {  $xml .= $data; }fclose( $f );preg_match_all( "//<book/>(.*?)/<//book/>/s", $xml, $bookblocks );foreach( $bookblocks[1] as $block ){preg_match_all( "//<author/>(.*?)/<//author/>/", $block, $author );preg_match_all( "//<title/>(.*?)/<//title/>/",  $block, $title );preg_match_all( "//<publisher/>(.*?)/<//publisher/>/", $block, $publisher );echo( $title[1][0]." - ".$author[1][0]." - ".$publisher[1][0]."/n" );}?>

4.解析XML到数组

<?php  $data = "<root><line /><content language=/"gb2312/">简单的XML数据</content></root>";  $parser = xml_parser_create(); //创建解析器  xml_parse_into_struct($parser, $data, $values, $index); //解析到数组  xml_parser_free($parser); //释放资源  //显示数组结构  echo "/n索引数组/n";  print_r($index);  echo "/n数据数组/n";  print_r($values);?>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表