PHP用SAX解析XML的实现代码与问题分析
前端之家收集整理的这篇文章主要介绍了
PHP用SAX解析XML的实现代码与问题分析,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<div class="codetitle"><a style="CURSOR: pointer" data="1250" class="copybut" id="copybut1250" onclick="doCopy('code1250')"> 代码如下:
<div class="codebody" id="code1250">
<?
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";
}
?>