使用 DOM 库读取 XML
 

 
  
  1. <?php  
  2. $doc = new DOMDocument();  
  3. $doc->load( '1.xml' );  
  4.  
  5. $books = $doc->getElementsByTagName( "book" );  
  6. foreach$books as $book )  
  7. {  
  8. $authors = $book->getElementsByTagName( "author" );  
  9. $author = $authors->item(0)->nodeValue;  
  10.  
  11. $publishers = $book->getElementsByTagName( "publisher" );  
  12. $publisher = $publishers->item(0)->nodeValue;  
  13.  
  14. $titles = $book->getElementsByTagName( "title" );  
  15. $title = $titles->item(0)->nodeValue;  
  16.  
  17. echo "$title - $author - $publisher\n";  
  18. }  
  19. ?>  

用 SAX 解析器读取 XML
用正则表达式解析 XML;

 

 
  
  1. <?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'1.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. ?>  

 

 
  
  1. <?php  
  2. $xml = "";  
  3. $f = fopen'1.xml''r' );  
  4. while$data = fread$f, 4096 ) ) { $xml .= $data; }  
  5. fclose( $f );  
  6.  
  7. preg_match_all( "/\<book\>(.*?)\<\/book\>/s",   
  8. $xml$bookblocks );  
  9.  
  10. foreach$bookblocks[1] as $block )  
  11. {  
  12. preg_match_all( "/\<author\>(.*?)\<\/author\>/",   
  13. $block$author );  
  14. preg_match_all( "/\<title\>(.*?)\<\/title\>/",   
  15. $block$title );  
  16. preg_match_all( "/\<publisher\>(.*?)\<\/publisher\>/",   
  17. $block$publisher );  
  18. echo$title[1][0]." - ".$author[1][0]." - ".  
  19. $publisher[1][0]."\n" );  
  20. }  
  21. ?>