Example code for PHP methods to read XML files

Source: Internet
Author: User
Tags fread xml parser

This article summarizes the way PHP reads XML format files. Share to everyone for your reference, 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 the XML with the SAX parser:

<?php$g_books = Array (); $g _elem = Null;function startelement ($parser, $name, $attrs) {    global $g _books, $g _elem;< C1/>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 ($par Ser, $data);} Xml_parser_free ($parser); foreach ($g _books as $book) {    echo $book [' TITLE ']. "-". $book [' AUTHOR ']. "-";    echo $book [' PUBLISHER ']. \ n ";}?" >

3. Parse the XML with a regular expression:

<?php$xml = ""; $f = fopen (' books.xml ', ' R '), while ($data = Fread ($f, 4096)) {  $xml. = $data;} Fclose ($f);p Reg_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. Parsing XML to an array

<?php  $data = "<root><line/><content language=\" gb2312\ "> Simple XML Data </content></ Root> ";  $parser = Xml_parser_create (); Create parser  xml_parse_into_struct ($parser, $data, $values, $index);//parse to array  xml_parser_free ($parser);//Release resources  //display array structure  echo "\ n indexed array \ n";  Print_r ($index);  echo "\ n data array \ n";  Print_r ($values);? >

5. Check that the XML is valid

<?php//Create XML parser $xml _parser = Xml_parser_create ();  Use case folding to ensure that these element names can be found in an array of elements xml_parser_set_option ($xml _parser, xml_option_case_folding, true);  Read XML file $xmlfile = "Bb.xml"; if (! (  $fp = fopen ($xmlfile, "R")) {die ("cannot read XML file $xmlfile");      }//Parse XML file $has _error = false; The flag bit while ($data = Fread ($fp, 4096)) {//loops through the XML document, only to EOF of the document, and stops parsing if (!xml_parse ($xml _parser, $data, feof ($FP)      ) {$has _error = true;    Break }} if ($has _error) {echo "The XML document is wrong!    <br/> ";    Output error rows, columns and their error messages $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 ("[%d rows,%d columns]:%s", $error _line, $error _row, $error _string);  Echo $message; } else {echo "The XML document is well-structured.  "; }//Close XML parser pointer, release resource Xml_parser_free ($xml _parser);? >

6. Can be used for accurate reading of XML

Test.xml

<?xml version= "1.0" encoding= "UTF-8"?>  <SBMP_MO_MESSAGE>    <connect_id>100</connect_ id>    <MO_MESSAGE_ID>123456</MO_MESSAGE_ID>    <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 </STATE_NAME>    <TP_PID> 0</tp_pid>    <TP_UDHI>0</TP_UDHI>    <MSISDN>15933626501</MSISDN>    < message_type>8</message_type>    <message>5618 Perennial supply seedlings, varieties have magnolia, yellow leaf Yang and so on. Contact Person: 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      Parse XML $xml = simplexml_load_string ($file);        if ($xml) {//echo $this->result;        Gets 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{1,2}/", $MESSAGE, $code); Switch ($codE[0]) {case 5618: $myData [message] = $MESSAGE;          Break Default: $myData [] = ' no short message.            ';          Break }} else {echo "Error loading XML file.        ";    }} catch (Exception $e) {Print_r ($e); }} else {echo ' does not have the XML file. ";} echo "<pre>";p Rint_r ($myData), echo "

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.