Summary of how PHP reads XML files, and how php reads xml files

Source: Internet
Author: User

Summary of how PHP reads XML files, and how php reads xml files

This example summarizes how PHP reads XML files. We will share this with you for your reference. The details are as follows:

Books. xml file:

<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>

1. DOMDocument Method

<?php$doc = new DOMDocument();$doc->load( 'books.xml' );$books = $doc->getElementsByTagName( "book" );foreach( $books as $book ){$authors = $book->getElementsByTagName( "author" );$author = $authors->item(0)->nodeValue;$publishers = $book->getElementsByTagName( "publisher" );$publisher = $publishers->item(0)->nodeValue;$titles = $book->getElementsByTagName( "title" );$title = $titles->item(0)->nodeValue;echo "$title - $author - $publisher\n";echo "<br>";}?>

2. Read XML with a SAX Parser:

<?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";}?>

3. parse XML using regular expressions:

<?php$xml = "";$f = fopen( 'books.xml', 'r' );while( $data = fread( $f, 4096 ) ) {  $xml .= $data; }fclose( $f );preg_match_all( "/\<book\>(.*?)\<\/book\>/s", $xml, $bookblocks );foreach( $bookblocks[1] as $block ){preg_match_all( "/\<author\>(.*?)\<\/author\>/", $block, $author );preg_match_all( "/\<title\>(.*?)\<\/title\>/",  $block, $title );preg_match_all( "/\<publisher\>(.*?)\<\/publisher\>/", $block, $publisher );echo( $title[1][0]." - ".$author[1][0]." - ".$publisher[1][0]."\n" );}?>

4. parse XML to the array

<? Php $ data = "<root> <line/> <content language = \" gb2312 \ "> simple XML data </content> </root> "; $ parser = xml_parser_create (); // create the parser xml_parse_into_struct ($ parser, $ data, $ values, $ index); // parse it to the array xml_parser_free ($ parser ); // release resources // display the array structure echo "\ n index Array \ n"; print_r ($ index); echo "\ n data array \ n "; print_r ($ values);?>

5. Check whether XML is valid

<? Php // create an XML Parser $ xml_parser = xml_parser_create (); // use case-insensitive folding to ensure that the element names xml_parser_set_option ($ xml_parser, XML_OPTION_CASE_FOLDING, true) can be found in the element array ); // read the XML file $ xmlfile = "bb. xml "; if (! ($ Fp = fopen ($ xmlfile, "r") {die ("unable to read XML file $ xmlfile");} // Parse XML file $ has_error = false; // flag while ($ data = fread ($ fp, 4096) {// read the XML document cyclically, only to the EOF of the document, and stop parsing if (! Xml_parse ($ xml_parser, $ data, feof ($ fp) {$ has_error = true; break ;}} if ($ has_error) {echo "This XML document is incorrect! <Br/> "; // Output Error row, column, and error message $ error_line = xml_get_current_line_number ($ xml_parser); $ error_row = xml_get_current_column_number ($ xml_parser ); $ error_string = xml_error_string (xml_get_error_code ($ xml_parser); $ message = sprintf ("[row % d, column % d]: % s", $ error_line, $ error_row, $ error_string); echo $ message;} else {echo "the XML document is well structured. ";}// Close the XML Parser pointer and release the resource xml_parser_free ($ xml_parser);?>

6. It can be used to accurately read XML

Test. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <SBMP_MO_MESSAGE> <CONNECT_ID> 100 </CONNECT_ID> <MO_MESSAGE_ID> 123456 </strong> <RECEIVE_DATE> 20040605 </RECEIVE_DATE> <RECEIVE_TIME> 153020 </RECEIVE_TIME> <GATEWAY_ID> 1 /GATEWAY_ID> <VALID> 1 </VALID> <CITY_CODE> 010 </CITY_CODE> <CITY_NAME> Beijing </CITY_NAME> <STATE_CODE> 010 </STATE_CODE> <STATE_NAME> Beijing </VALID> /STATE_NAME> <TP_PID> 0 </TP_PID> <TP_UDHI> 0 </TP_UDHI> <MSISDN> 15933626501 </MSISDN> <MESSAGE_TYPE> 8 </M ESSAGE_TYPE> <MESSAGE> 5618 perennial seedling supply, varieties such as Magnolia and Yellow Leaf Yang. Contact: Zhang San, tel: 1234567890. </MESSAGE> <LONG_CODE> 100 </LONG_CODE> <SERVICE_CODE> 9588 </SERVICE_CODE> </SBMP_MO_MESSAGE>

Test. php:

<? Php $ myData = array (); $ file = file_get_contents ("test. xml"); if (strpos ($ file, '<? Xml ')>-1) {try {// load parsing xml $ xml = simplexml_load_string ($ file); if ($ xml) {// echo $ this-> result; // get the node value $ CONNECT_ID = $ xml-> CONNECT_ID; $ MO_MESSAGE_ID = $ xml-> MO_MESSAGE_ID; $ RECEIVE_DATE = $ xml-> RECEIVE_DATE; $ RECEIVE_TIME = $ xml-> RECEIVE_TIME; $ GATEWAY_ID = $ xml-> GATEWAY_ID; $ VALID = $ xml-> VALID; $ CITY_CODE = $ xml-> CITY_CODE; $ CITY_NAME = $ xml-> CITY_NAME; $ STATE_CODE = $ xml-> CITY_CODE; $ STATE _ NAME = $ xml-> STATE_NAME; $ TP_PID = $ xml-> TP_PID; $ TP_UDHI = $ xml-> TP_UDHI; $ MSISDN = $ xml-> MSISDN; $ MESSAGE_TYPE = $ xml-> MESSAGE_TYPE; $ MESSAGE = $ xml-> MESSAGE; // SMS $ LONG_CODE = $ xml-> LONG_CODE; $ SERVICE_CODE = $ xml-> SERVICE_CODE; preg_match ("/(561) \ d {5618}/", $ MESSAGE, $ code); switch ($ code [0]) {case: $ myData [message] = $ MESSAGE; break; default: $ myData [] = 'No short message. '; Break ;}} An error occurred while loading the xml file in else {echo. ";}} Catch (exception $ e) {print_r ($ e) ;}} else {echo" does not have this XML file. ";}Echo" <pre> "; print_r ($ myData); echo" 

PS: Here are some online tools for xml operations for your reference:

Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson

Online formatting XML/online compression XML:
Http://tools.jb51.net/code/xmlformat

XMLOnline compression/formatting tools:
Http://tools.jb51.net/code/xml_format_compress

XMLCode Online formatting and beautification tools:
Http://tools.jb51.net/code/xmlcodeformat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.