<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>
|
<?php
$g_books = array();
$g_elem = null;
//該函數爲讀取一個標籤時作的處理,$name獲取標籤的名稱,該處將標籤名賦給$g_elem,在讀取該標籤內容時作判斷。如果標籤是BOOK就在$g_books []中新增一個元素,$g_books []是一個二維數組
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" );
//該處我們是直接處理字符串,則不需要讀取文件這一步驟,直接運行//xml_parse( $parser, $data );
$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";
}
?>
|
|