PHP用SAX解析XML

 <?php
 2
 $g_books = array();
 3
 $g_elem = null;
 4
 
 5 function startElement( $parser, $name, $attrs ) 
 6
 {
 7
 global $g_books, $g_elem;
 8
 if ( $name == 'BOOK' ) $g_books []= array();
 9
 $g_elem = $name;
10
 }
11
 
12 function endElement( $parser, $name ) 
13
 {
14
 global $g_elem;
15
 $g_elem = null;
16
 }
17
 
18 function textData( $parser, $text )
19
 {
20
 global $g_books, $g_elem;
21
 if ( $g_elem == 'AUTHOR' ||
22 $g_elem == 'PUBLISHER' ||
23 $g_elem == 'TITLE' )
24
 {
25
 $g_bookscount$g_books ) - 1 ][ $g_elem ] = $text;
26
 }
27
 }
28
 
29 $parser = xml_parser_create();
30
 
31 xml_set_element_handler$parser, "startElement", "endElement" );
32
 xml_set_character_data_handler$parser, "textData" );
33
 
34 $f = fopen'books.xml', 'r' );
35
 
36 while$data = fread$f, 4096 ) )
37
 {
38
 xml_parse$parser, $data );
39
 }
40
 
41 xml_parser_free$parser );
42
 
43 foreach$g_books as $book )
44
 {
45
 echo $book['TITLE']." - ".$book['AUTHOR']." - ";
46
 echo $book['PUBLISHER']."\n";
47
 }
48
 ?>

原文地址:https://www.cnblogs.com/CodeGuy/p/2146307.html