Create and parse XML in PHP

Source: Internet
Author: User

As XML continues to heat up, PHP provides a large number of standard libraries (class libraries) dedicated to XML processing to manipulate XML. For example, dom xml extension rewriting, SimpleXML extension, SOAP extension, and XMLReader and XMLWrite extension of PHP5.1.


1. Use SimpleXML to manipulate XML

There are two traditional approaches to processing XML files: SAX and DOM. Based on the event trigger mechanism, SAX performs a scan on the XML file to complete the processing. DOM constructs the entire XML file into a DOM tree and completes the processing by traversing the DOM tree. These two methods have their own advantages and disadvantages. The processing logic of SAX is relatively abstract, and the DOM processing process is relatively cumbersome, which is not suitable for beginners. PHP5 introduces a new set of XML processing functions, namely SimpleXML. For example, SimpleXML is compact and provides only a few method functions, but it is very powerful and easy to use to process XML files.


[Php] view plaincopy
1. Create an XML file
 
$ _ Xml = <xml
 
<? Xml version = "1.0" encoding = "UTF-8"?>
 
<Root>
 
<Version> 1.0 </version>
 
<Info> xml parsing test </info>
 
<User>
 
<Name> eliminate dust </name>
 
<Url> http://www.google.com.hk </url>
 
<Author sex = "male"> Yang ze </author>
 
</User>
 
<User>
 
<Name> CSDN </name>
 
<Url> http://www.csdn.net </url>
 
<Author sex = "female"> who and who </author>
 
</User>
 
<User>
 
<Name> donkey </name>
 
<Url> http://www.verycd.com </url>
 
<Author sex = "male"> surnamed Huang </author>
 
</User>
 
</Root>
 
Xml;
 
$ _ Sxe = new SimpleXMLElement ($ _ xml); // create an object to parse an xml string
 
$ _ Sxe-> asXML ('test. xml'); // generate an xml file
 

 
2. load XML files
 
$ _ Sxe = simplexml_load_file ("test. xml"); // load the XML file
 
Var_dump ($ _ sxe); // output related information
 
Print_r ($ _ sxe); // output main information
 
Reflection: export (new ReflectionClass ($ sxe); // use Reflection to View Details
 

 
3. parse XML files
 
$ _ Sxe = simplexml_load_file ("test. xml"); // load the XML file
 
Var_dump ($ _ sxe); // output related information
 
Print_r ($ _ sxe); // output main information
 
Reflection: export (new ReflectionClass ($ _ sxe); // View Details with launch
 
Echo $ _ sxe-> asXML (); // print the entire XML
 

 
4. Read XML data
 
$ _ Sxe = simplexml_load_file ("test. xml ");
 
// Read the value of the first-level node, such as the version label
 
Echo $ _ sxe-> version;
 
// If there are multiple subscripts, you can set their subscripts.
 
Echo $ _ sxe-> version [2];
 
// If you want to print all data, use traversal.
 
Foreach ($ _ sxe-> version as $ _ version ){
 
Echo '['. $ _ version. ']';
 
}
 
// Access the name of the second-level node
 
Echo $ _ sxe-> user [1]-> name;
 
// Obtain the name value of all secondary nodes
 
Foreach ($ _ sxe-> user as $ _ user ){
 
Echo '['. $ _ user-> name. ']';
 
}
 
// Obtain the label attributes of the second-level node
 
Echo $ _ sxe-> user [1]-> author-> attributes ();
 

 
5. Use XPath to get nodes
 
$ _ Sxe = simplexml_load_file ("test. xml ");
 
// Use XPath to obtain the node information www.2cto.com
 
$ _ Version = $ _ sxe-> xpath ('/root/version ');
 
Echo $ _ version [1];
 
// Traverse version
 
Foreach ($ _ version as $ _ v ){
 
Echo '['. $ _ v. ']';
 
}
 
// Access the second-level node
 
$ _ User = $ _ sxe-> xpath ('/root/user ');
 
Echo $ _ use r [2]-> name;
 
// Traverse the second-level node
 
Foreach ($ _ user as $ _ u ){
 
Echo '['. $ _ u-> name. ']';
 
}
 
// Access attributes
 
Echo $ _ user [1]-> author-> attributes ();
 

2. Use DOMDocument to manipulate XML

In many cases, manually generating tags requires that documents be generated from top to bottom. You must ensure that the tags are complete, including the start and end tags. Although some PHP functions or classes can be improved, PHP also provides a set of more helpful built-in objects and functions. The Document Object Model (DOM) provides a tree structure that allows you to easily create and process tags.
[Php] view plaincopy
1. DOMDocument parsing XML
 
// Create a DOMDocument ()
 
$ _ Doc = new DOMDocument ();
 
// Load xml
 
$ _ Doc-> load ('test. xml ');
 
// Obtain the version label
 
$ _ Version = $ _ doc-> getElementsByTagName ('version ');
 
Echo $ _ version-> item (2)-> nodeValue;
 
// Traverse the version label
 
Foreach ($ _ version as $ v ){
 
Echo $ v-> nodeValue;
 
}
 
2. DOMDocument generates XML
 
// Declare xml
 
$ _ Doc = new DOMDocument ('1. 0', 'utf-8 ');
 
// Typographical format
 
$ _ Doc-> formatOutput = true;
 
// Create a master tag
 
$ _ Root = $ _ doc-> createElement ('root ');
 
// Create a first-level label version
 
$ _ Version = $ _ doc-> createElement ('version ');
 
// Assign a value to the version label
 
$ _ VersionTextNode =$ _ doc-> createTextNode ('1. 0 ');
 
// Add the value to the version label
 
$ _ Version-> appendChild ($ _ versionTextNode );
 
// Add the first-level label version to the root
 
$ _ Root-> appendChild ($ _ version );
 
// Write the master tag to xml
 
$ _ Doc-> appendChild ($ _ root );
 
// Generate xml
 
$ _ Doc-> save ('aaa. xml ');
 


From geniusxiaoyu's column

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.