PHP read XML-PHP source code

Source: Internet
Author: User
PHP reads XML php reads xml

1. php code

Books. xml file:
 
  
   
Jack Herrington
   PHP Hacks
   
    
O 'Reilly
   
  
  
   
Jack Herrington
   Podcasting Hacks
   
    
O 'Reilly
   
  
 1. DOMDocument method
 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"
";}?> 2. read XML with a SAX parser 3. parse XML using regular expressions (.*?) \ <\/Book \>/s ", $ xml, $ bookblocks); foreach ($ bookblocks [1] as $ block) {preg_match_all ("/\(.*?) \ <\/Author \>/", $ block, $ author); preg_match_all ("/\ (.*?) \ <\/Title \>/", $ block, $ title); preg_match_all ("/\ (.*?) \ <\/Publisher \>/", $ block, $ publisher); echo ($ title [1] [0]. "-". $ author [1] [0]. "-". $ publisher [1] [0]. "\ n") ;}?> 4. parse XML to several groups Simple XML data "; $ 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 "; // Output error row, column and error information $ 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 XMLtest. xml 100 123456 20040605 153020 1 1 010 Beijing 010 Beijing 0 0 15933626501 8 5618 perennial supply of seedlings, varieties of Magnolia, yellow leaf Yang and so on. Contact: Zhang San, tel: 1234567890. 100 9588 Test. php: -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"
"; print_r($myData); echo ""; echo $myData[message]; ?>

2. four methods for generating XML files in PHP

[Preface] how to create an XML file using PHP? It has always been a class encapsulated by others. I have never tried it myself. it is rare to take a few days off, so I have summarized it myself. Four common methods for generating XML files using PHP are as follows: [XML file content]
        
            
     Title1        
     
      
Content1
             
     
      
2009-10-11
         
        
            
     Title2        
     
      
Content2
             
     

         
    [Directly generate a string] Method 1: generate a string using pure PHP code, and write this string into a file suffixed with XML. This is the most primitive method for generating XML, but it is valid! The PHP code is as follows:
    'Title1', 'content' => 'content1', 'pubdate' => '2017-10-11 ',), array ('title' => 'title2 ', 'content' => 'content2', 'pubdate' => '2017-11-11 ',); $ title_size = 1; $ xml ="
    \ N "; $ xml. = "\ n"; foreach ($ data_array as $ data) {$ xml. = create_item ($ data ['title'], $ title_size, $ data ['content'], $ data ['pubdate']);} $ xml. ="\ N "; echo $ xml; // Create an XML single function create_item ($ title_data, $ title_size, $ content_data, $ pubdate_data) {$ item ="
    
     
\ N "; $ item. ="
     ". $ Title_data ."\ N "; $ item. ="
     
      
". $ Content_data ."
     \ N "; $ item. ="
     
      
". $ Pubdate_data ."
     \ N "; $ item. ="
    \ N "; return $ item ;}?> [DomDocument] Method 2: Use DomDocument to generate an XML file and create a node using the createElement method. use the createTextNode method to create text content and add a subnode using the appendChild method. The PHP code for creating an attribute using the createAttribute method is as follows:
    'Title1', 'content' => 'content1', 'pubdate' => '2017-10-11 ',), array ('title' => 'title2 ', 'content' => 'content2', 'pubdate' => '2017-11-11 ',)); // attribute array $ attribute_array = array ('title' => array ('size' => 1); // Create an XML document and set the XML version and encoding .. $ Dom = new DomDocument ('1. 0 ', 'utf-8'); // create the root node $ article = $ dom-> createElement ('article'); $ dom-> appendchild ($ article ); foreach ($ data_array as $ data) {$ item = $ dom-> createElement ('ITEM'); $ article-> appendchild ($ item); create_item ($ dom, $ item, $ data, $ attribute_array);} echo $ dom-> saveXML (); function create_item ($ dom, $ item, $ data, $ attribute) {if (is_array ($ data) {foreach ($ data as $ key => $ val) {// Create an element $ key = $ dom-> createElement ($ key); $ item-> appendchild ($ key ); // create an element value $ text = $ dom-> createTextNode ($ val); $ key-> appendchild ($ text ); if (isset ($ attribute [$ key]) {// if this field has related attributes, you need to set foreach ($ attribute [$ key] as $ akey => $ row) {// Create an attribute node $ akey = $ dom-> createAttribute ($ akey); $ key-> appendchild ($ akey ); // Create an attribute value node $ aval = $ dom-> createTextNode ($ row); $ akey-> appendChild ($ aval) ;}// e Nd if }}// end if} // end function?> (XMLWriter) method 3: Use the XMLWriter class to create XML files this method is valid after PHP 5.1.2. In addition, it can output multiple types of encoded XML, but the input can only be the utf-8PHP code as follows:
    'Title1', 'content' => 'content1', 'pubdate' => '2017-10-11 ',), array ('title' => 'title2 ', 'content' => 'content2', 'pubdate' => '2017-11-11 ',)); // attribute array $ attribute_array = array ('title' => array ('size' => 1); $ xml = new XMLWriter (); $ xml-> openUri ("php: // output"); // The output mode. you can also set it to an xml file address, output directly to the file $ xml-> setIndentString (''); $ xml-> setIndent (true); $ xml-> startDocument ('1. 0', 'utf-8'); // start to create a file // root Node $ xml-> startElement ('article'); foreach ($ data_array as $ data) {$ xml-> startElement ('ITEM'); if (is_array ($ data )) {foreach ($ data as $ key => $ row) {$ xml-> startElement ($ key); if (isset ($ attribute_array [$ key]) & is_array ($ attribute_array [$ key]) {foreach ($ attribute_array [$ key] as $ akey => $ aval) {// Set the attribute value $ xml-> writeAttribute ($ akey, $ aval) ;}}$ xml-> text ($ row ); // set the content $ xml-> endElement ();// $ Key }}$ xml-> endElement (); // item} $ xml-> endElement (); // article $ xml-> endDocument (); $ xml-> flush ();?> [SimpleXML] method 4: Use SimpleXML to create an XML document
    'Title1', 'content' => 'content1', 'pubdate' => '2017-10-11 ',), array ('title' => 'title2 ', 'content' => 'content2', 'pubdate' => '2017-11-11 ',)); // attribute array $ attribute_array = array ('title' => array ('size' => 1); $ string = <
    
     
XML; $ xml = simplexml_load_string ($ string); foreach ($ data_array as $ data) {$ item = $ xml-> addChild ('ITEM '); if (is_array ($ data) {foreach ($ data as $ key => $ row) {$ node = $ item-> addChild ($ key, $ row ); if (isset ($ attribute_array [$ key]) & is_array ($ attribute_array [$ key]) {foreach ($ attribute_array [$ key] as $ akey => $ aval) {// Set the attribute value $ node-> addattriey ($ akey, $ aval) ;}}} echo $ xml-> asXML ();? >
    

3. five methods for XML parsing in PHP

[Use DomDocument to parse]
    Load ($ url); */$ elements = $ dom-> getElementsByTagName ("current_conditions"); $ element = $ elements-> item (0 ); $ condition = get_google_xml_data ($ element, "condition"); $ temp_c = get_google_xml_data ($ element, "temp_c"); echo 'weather: ', $ condition ,'
'; Echo 'temperature:', $ temp_c ,'
'; Function get_utf8_string ($ content) {// Convert some characters to utf8 format $ encoding = mb_detect_encoding ($ content, array ('ascii', 'utf-8 ', 'gb2312', 'gbk', 'big5'); return mb_convert_encoding ($ content, 'utf-8', $ encoding);} function get_google_xml_data ($ element, $ tagname) {$ tags = $ element-> getElementsByTagName ($ tagname); // get all $ tagname $ tag = $ tags-> item (0 ); // obtain the first tag named $ tagname if ($ tag-> hasAttributes ()){// Get data attributes $ attribute = $ tag-> getAttribute ("data"); return $ attribute;} else {return false ;}}?> This is just a simple example. it only includes loadXML, item, getAttribute, getElementsByTagName, and other methods. There are also some useful methods based on your actual needs. [XMLReader] when we use php to interpret xml content, there are many objects that provide functions, so that we do not need to parse them one by one, as long as the tag and attribute names are used, you can retrieve the attributes and content in the file, which is much more convenient. XMLReader browses the nodes of the xml file in sequence. it can be imagined that the cursor passes through the nodes of the entire file and captures the required content. Open ($ url); $ condition = ''; $ temp_c =''; while ($ xml-> read () {// echo $ xml-> name, "==>", $ xml-> depth ,"
"; If (! Empty ($ condition )&&! Empty ($ temp_c) {break;} if ($ xml-> name = 'condition' & empty ($ condition )) {// obtain the first condition $ condition = $ xml-> getAttribute ('data ');} if ($ xml-> name = 'temp _ c' & empty ($ temp_c )) {// obtain the first temp_c $ temp_c = $ xml-> getAttribute ('data');} $ xml-> read () ;}$ xml-> close (); echo 'weather: ', $ condition ,'
'; Echo 'temperature:', $ temp_c ,'
'; We just need to take the first condition and the first temp_c, so we traverse all the nodes, write the first condition and the first temp_c into the variable, and finally output the result. [DOMXPath] This method requires the use of the DOMDocument object to create the structure of the entire document, Load ($ url); $ xpath = new DOMXPath ($ dom); $ element = $ xpath-> query ("/xml_api_reply/weather/current_conditions ") -> item (0); $ condition = get_google_xml_data ($ element, "condition"); $ temp_c = get_google_xml_data ($ element, "temp_c"); echo 'weather :', $ condition ,'
'; Echo 'temperature:', $ temp_c ,'
'; Function get_google_xml_data ($ element, $ tagname) {$ tags = $ element-> getElementsByTagName ($ tagname ); // Obtain all $ tagname $ tag = $ tags-> item (0); // obtain the first tag named $ tagname if ($ tag-> hasAttributes ()) {// get data attributes $ attribute = $ tag-> getAttribute ("data"); return $ attribute;} else {return false ;}}?> [Xml_parse_into_struct] description: int xml_parse_into_struct (resource parser, string data, array & values [, array & index]) This function resolves the XML file to two corresponding arrays, the index parameter contains a pointer to the corresponding value in the values array. The last two array parameters can be passed to the function by pointers. Note: If xml_parse_into_struct () fails, 0 is returned, and 1 is returned. This is different from FALSE and TRUE. pay attention when using the = operator for example. '; Echo' temperature: ', $ vals [$ index ['temp _ c'] [0] ['bubuckets'] ['data'],'
'; [Simplexml] This method is available in PHP5. This example is available in the official google documentation, as follows: // Charset: UTF-8/*** use php Simplexml to call the google weather forecast api, unlike g official examples * google official php domxml get google weather forecast example * http://www.google.com/tools/toolbar/buttons/intl/zh-CN/apis/howto_guide.html ** @ copyright Copyright (c) 2008 * @ License New BSD License * @ version 2008-11-9 * // city, using city pinyin $ city = empty ($ _ GET ['city'])? 'Shenzhen': $ _ GET ['city']; $ content = file_get_contents ("http://www.google.com/ig/api? Weather = $ city & hl = zh-cn "); $ content | die (" No such city's data "); $ content = mb_convert_encoding ($ content, 'utf-8', 'gbk'); $ xml = simplexml_load_string ($ content); $ date = $ xml-> weather-> forecast_information-> forecast_date-> attributes (); $ html = $ date."
\ R \ n "; $ current = $ xml-> weather-> current_conditions; $ condition = $ current-> condition-> attributes (); $ temp_c = $ current-> temp_c-> attributes (); $ humidity = $ current-> humidity-> attributes (); $ icon = $ current-> icon-> attributes (); $ wind = $ current-> wind_condition-> attributes (); $ condition & $ condition = $ xml-> weather-> forecast_conditions-> condition-> attributes (); $ icon & $ icon = $ xml-> weather-> forecast_conditions-> icon-> attributes (); $ html. = "current: {$ condition}, {$ temp_c} °C, {$ humidity} {$ wind}
\ R \ n "; foreach ($ xml-> weather-> forecast_conditions as $ forecast) {$ low = $ forecast-> low-> attributes (); $ high = $ forecast-> high-> attributes (); $ icon = $ forecast-> icon-> attributes (); $ condition = $ forecast-> condition-> attributes (); $ day_of_week = $ forecast-> day_of_week-> attributes (); $ html. = "{$ day_of_week }:{$ high}/{$ low} °C, {$ condition}
\ R \ n ";} header ('content-type: text/html; Charset: utf-8 '); print $ html;?>
Related Article

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.