Php xml read/write operation implementation code

Source: Internet
Author: User
Tags foreach xpath

What is XML?
XML (eXtensible Markup Language) is a subset of the standard general Markup Language SGML of the International Organization for Standardization. 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:

Ability to coordinate work as a whole
Is a standardized XML Library: libxml2
Fully complies with W3C specifications
More effective data processing
Is an appropriate XML tool in 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 are the differences between XML and 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. Web pages, wml displayed on mobile phones, and display on other media terminals
Vendor and platform 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 end mark.
XML has only one root element.
Attribute must be enclosed in quotation marks
What does a complete XML look like?

The code is as follows: Copy code
<? Xml version = "1.0"?>
<Shows>
<Show>
<Name> Simpsons </name>
<Channel> FOX </channel>
<Start> 8: 00 PM </start>
<Duration> 30 </duration>
</Show>
<Show>
<Name> Law & Order </name>
<Channel> NBC </channel>
<Start> 8: 00 PM </start>
<Duration> 60 </duration>
</Show>
</Shows>

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, and all other elements are its child elements.
Correct empty element formatting
Case-sensitive matching of tags
Correct nesting
Attribute values must be enclosed in quotation marks.
The object must be declared before being referenced.
Entities cannot point to themselves cyclically
Use DOM to generate XML
 

The code is as follows: Copy code

// Create a new document $ dom = new DOMDocument ('1. 0 ');
// Create a root element <book> and 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:

The code is as follows: Copy code
<? Xml version = "1.0"?>
<Book?>
<Cover = "soft"> PHP Cookbook </title>
</Book>

Use PHP to parse existing XML files
There are three common methods to parse XML files.

Use SimpleXML for simple files
Use DOM extension for complex XML files
XMLReader extension for large XML files
The XML sample file is as follows (address-book.xml ):

The code is as follows: Copy code

<? Xml version = "1.0"?>
<Address-book>
<Person id = "1">
<! -- David Sklar -->
<Firstname> David </firstname>
<Lastname> Sklar </lastname>
<City> New York </city>
<State> NY </state>
<Email> sklar@php.net </email>
</Person>

<Person id = "2">
<! -- Adam Trachtenberg -->
<Firstname> Adam </firstname>
<Lastname> Trachtenberg </lastname>
<City> San Francisco </city>
<State> CA </state>
<Email> amt@php.net </email>
</Person>
</Address-book>

SimpleXML:

The code is as follows: Copy code

$ 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 ";

} DOM extension:

 

The code is as follows: Copy code

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

XMLReader extension:

The code is as follows: Copy code

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

Use XPath to query information http://www.111cn.net
XPath is available in SimpleXML and DOM extensions.

The code is as follows: Copy code

// SimpleXml example
$ Emails = $ s-> xpath ('/address-book/preson/e-mail ');

// DOM extension example

The code is as follows: Copy code
$ 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: Copy code

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

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.