Php xml read/write operation implementation code

Source: Internet
Author: User
The document explains how to use php to read, write, delete, and edit xml documents, from the basics of xml to the examples, you can add this article to favorites if you need it. what is XML? XML (eXtensibleM... the document explains how to use php to read, write, delete, and edit xml documents, from the basics of xml to the examples, you can add this article to favorites if you need it.

What is XML?

XML (eXtensible Markup Language) is a subset of the standard general Markup Language SGML of the International Organization for Standardization (ISO). It consists of the following specifications:

EXtensible Sytle Language (XSL)

XML Linking Language (including Xpath, Xlink, and Xpointer)

XML Namespace)

There are many problems with XML processing in versions earlier than PHP5. for example, XML tools only have simple associations, and each tool cannot work together, the new XML extension in PHP5 has the following features:

The ability to coordinate work as a whole is a standardized XML Library: libxml2, which fully complies with W3C specifications and processes data more effectively. it is a suitable XML tool for your work.

What is the difference and connection between HTML and XML?

HTML and XML are both subset of SGML, so they have great similarity. below is the uniqueness of XML compared with HTML:

Scalability to define new tags. This makes sense for today's web

Structure, used to represent data of any complexity. In a sense, it is a small relational database.

Check to check the structure correctness of the data. This can be achieved through DTD constraints.

Media independence: content is published in multiple formats. wml is displayed on webpages, mobile phones, and other media terminals. the vendor and platform are neutral, data representation and content separation (this is essentially different from html, but the current popular design concept of DIV + CSS is similar to this ).

XML elements are case sensitive. any element must have an ending Mark. XML only has one root element, and attributes must be enclosed by quotation marks.

The code for a complete XML file is as follows:

 
      
           
   
    Simpsons
            
   
    FOX
            
   
    8:00 PM
            
   
    30
        
       
           
   
    Law & Order
            
   
    NBC
            
   
    8:00 PM
            
   
    60
        
   
 

A well-formed XML document must have the following characteristics:

Each element has a start and end mark. the document has only one root element. All other elements are its child elements. the empty elements are correctly formatted and the tags are case-sensitive, correct nesting. attribute values must be enclosed in quotation marks. objects must be declared before being referenced. objects cannot point to themselves cyclically.

Use DOM to generate XML. the code is as follows:

// Create a new document $ dom = new DOMDocument ('1. 0'); // Create a root element
 
  
Add it to the document $ book =$ dom-> appendChild ($ dom-> createElement ('book'); // create a title sub-element, and add it to $ book $ title = $ book-> appendChild ($ dom-> createElement ('title ')); // set the text and cover attributes of the title element $ title-> appendChild ($ dom-> createTextNode ('php Cookbook'); $ title-> setAttribute ('cover ', 'Soft'); // create and add the author element to $ book $ sklar = $ book-> appendChild ($ dom-> createElement ('author ')); // add text to the author node $ sklar-> appendChild ($ dom-> createTextNode ('sklar ')); $ trachtenberg = $ book-> appendChild ($ dom-> createElement ('author'); $ trachtenberg-> appendChild ($ dom-> createTextNode ('trachtenken ')); // output the perfectly formatted XML document $ dom-> formatOutput = true; echo $ dom-> saveXML (); // The output content is as follows:
 
 PHP Cookbook 

PHP is used to parse existing XML files. There are three common methods to parse XML files. SimpleXML is used for simple files and DOM extension is used for complex XML files, XMLReader extension is used for large XML files.

The XML sample file is the following address-book.xml with the code:

          
          
 
  David
          
 
  Sklar
          
 
  New York
          
 
  NY
          
 
  sklar@php.net
            
          
           
  
   Adam
           
  
   Trachtenberg
           
  
   San Francisco
           
  
   CA
           
  
   amt@php.net
       
  

The code in SimpleXML format is as follows:

$sx = simplexml_load_file('address-book.xml'); foreach ($sx->person as $person) {     $firstname_text_value = $person->firstname;     $lastname_text_value = $person->lastname;     print "$firstname_text_value $lastname_text_valuen"; }

The code for DOM extension is as follows:

$dom = new DOMDocument; $dom->load('address-book.xml');  foreach ($dom->getElementsByTagname('person') as $person) {     $firstname = $person->getElementsByTagname('firstname');     $firstname_text_value = $firstname->item(0)->firstChild->nodeValue;      $lastname = $person->getElementsByTagname('lastname');     $lastname_text_value = $lastname->item(0)->firstChild->nodeValue;      print "$firstname_text_value $lastname_text_valuen"; }

The code is as follows:

$reader = new XMLReader(); $reader->open('card-catalog.xml');  while ($reader->read()) {     if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'author') {         $reader->read();         print $reader->value . "n";     } }

XPath is available in SimpleXML and DOM extensions. the code is as follows:

// SimpleXml example $ emails = $ s-> xpath ('/address-book/preson/email'); // DOM extension example $ xpath = new DOMXPath ($ dom ); $ email = $ xpath-> query ('/address-book/preson/e-mail'); // verify whether the XML document is legal

In PHP, DOM extensions support verification based on DTD, XML Schema, and RelaxNG, while SimpleXML only provides XML Schema verification.

XML content in UTF-8 format

If the data source is in another format and needs to be encoded in UTF-8 format, the following is an example of conversion through the iconv library, the code is as follows:

$ Utf_8 = iconv ('ISO-8859-1 ', 'utf-8', $ iso_8859_1 );


Article address:

Reprint at will ^ please include the address of this 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.