用SAX解析XML的代码详解及问题分析
来源:爱站网时间:2021-07-01编辑:网友分享
熟悉和掌握一种解析XML文档的方法是很重要的,在HPH4服务器下,XML解析函数只能用SAX方式的xml_parser来解析了,下面内容中,爱站技术频道小编将为大家分享用SAX解析XML的代码详解及问题分析,感兴趣的朋友不要错过。
复制代码 代码如下:
$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";
}
?>
PHP中用SAX方式解析XML发现的问题
XML如下:
so.xml
复制代码 代码如下:
...(省略若干行)
xml_class.php
复制代码 代码如下:
class xml {
var $parser;
var $i =0;
var $search_result = array();
var $row = array();
var $data = array();
var $now_tag;
var $tags = array("ID", "CLASSID", "SUBCLASSID", "CLASSNAME", "TITLE", "SHORTTITLE", "AUTHOR", "PRODUCER", "SUMMARY", "CONTENT", "DATE");
function xml()
{
$this->parser = xml_parser_create();
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, "tag_open", "tag_close");
xml_set_character_data_handler($this->parser, "cdata");
}
function parse($data)
{
xml_parse($this->parser, $data);
}
function tag_open($parser, $tag, $attributes)
{
$this->now_tag=$tag;
if($tag=='RESULT') {
$this->search_result = $attributes;
}
if($tag=='ROW') {
$this->row[$this->i] = $attributes;
}
}
function cdata($parser, $cdata)
{
if(in_array($this->now_tag, $this->tags)){
$tagname = strtolower($this->now_tag);
$this->data[$this->i][$tagname] = $cdata;
}
}
function tag_close($parser, $tag)
{
$this->now_tag="";
if($tag=='ROW') {
$this->i++;
}
}
}
?>
search.php
以上就是爱站技术频道小编为大家分享的关于在php下用SAX解析XML的实现代码与问题分析,文中详细介绍了PHP中用SAX方式解析XML发现的问题的代码内容,有需要的话直接复制参考。