最新消息:网站改版咯

php读取xml

php Yovae 1277浏览

用php怎么读取xml内容以前没用到,最近一个项目需要就简单地了解了一下,总结一些方法,通过以下示例来简单介绍一下php读取xml文件的几种不同方式:

xml文件book.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>

使用 DOM 库读取 XML

读取的内容:

<?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";
}
?>

用 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";
}
?>

用正则表达式解析 XML;

<?php
$xml = "";
$f = fopen( 'books.xml', 'r' );
while( $data = fread( $f, 4096 ) ) { $xml .= $data; }
fclose( $f );

preg_match_all( "//&lt;book/&gt;(.*?)/&lt;//book/&gt;/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" );
}
?>

一般来说使用dom方式比较清晰易读。至于用说明方法就看具体应用情况了。

转载请注明:Yovae Studio » php读取xml