本文实例总结了PHP读取XML格式文件的方法。分享给大家供大家参考,具体如下:
books.xml文件:
rush:xml;">
Jack Herrington
PHP Hacks
O'Reilly
Jack Herrington
Podcasting Hacks
O'Reilly
1.DOMDocument方法
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 "
"; } ?>
"; } ?>
2.用 SAX 解析器读取 XML:
3.用正则表达式解析 XML:
(.*?)\<\/book\>/s",$xml,$bookblocks );
foreach( $bookblocks[1] as $block )
{
preg_match_all( "/\(.*?)\<\/author\>/",$block,$author );
preg_match_all( "/\(.*?)\<\/title\>/",$title );
preg_match_all( "/\(.*?)\<\/publisher\>/",$publisher );
echo( $title[1][0]." - ".$author[1][0]." - ".$publisher[1][0]."\n" );
}
?>
4.解析XML到数组
5.检查XML是否有效
"; //输出错误行,列及其错误信息 $error_line = xml_get_current_line_number($xml_parser); $error_row = xml_get_current_column_number($xml_parser); $error_string = xml_error_string(xml_get_error_code($xml_parser)); $message = sprintf("[第%d行,%d列]:%s",$error_line,$error_row,$error_string); echo $message; } else { echo "该XML文档是结构良好的。"; } //关闭XML解析器指针,释放资源 xml_parser_free($xml_parser); ?>