Generate and parse xml files in SimpleXML in php

Source: Internet
Author: User
There are many classes available for xml document operations in php. phpSimpleXML is a very good xml Parser. next I will give you two application instances. for example, to generate an xml document, the code is as follows: classSimp... we can use many classes for xml document operations in php. php SimpleXML is a very good xml Parser. I will give you two examples.

For example, the code for generating an xml document is as follows:

Class SimpleXMLExtended extends SimpleXMLElement {public function addCData ($ cdata_text) {$ node = dom_import_simplexml ($ this); $ no = $ node-> ownerDocument; $ node-> appendChild ($ no-> createCDATASection ($ cdata_text);} function array2xml ($ array, $ xml = false) {if ($ xml = false) {$ xml = new SimpleXMLExtended ('
 ');} Foreach ($ array as $ key => $ value) {if (is_array ($ value) {array2xml ($ value, $ xml-> addChild ($ key);} else {// if it contains Chinese characters, encode if (preg_match ("/([x81-xfe] [x40-xfe])/", $ value, $ match) {$ value = iconv ('gbk', 'utf-8', $ value);} $ xml-> $ key = NULL; // very important! We need a node where to append $ xml-> $ key-> addCData ($ value); // $ xml-> $ key-> addAttribute ('Lang ', 'en'); // $ xml-> addChild ($ key, $ value) ;}return $ xml-> asXML ();}

For example, SimpleXMLElement parses xml and the code is as follows:

   
    
  
   
HTTP
     
  
   
80
     
  
   
/Index.html
     
  
   
5000
     
  
   
3000
     
  
   
2
     
  
   
3
    
   
    
     
    
  XML; $ test = new SimpleXMLElement ($ content); // Obtain the ping_protocol value $ ping_protocol = $ test-> global_setting-> ping_protocol; echo "ping_protocol: $ ping_protocol n "; // Print the IP foreach ($ test-> instances-> instance as $ instance) {echo "IP: {$ instance ['IP']} n";} of all instances ";}


Address:

Reprinted at will, but please attach the article address :-)

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.