Basic Articles for developing XML applications in PHP add node delete node query Section

Source: Internet
Author: User
Tags php foreach

1. XML Introduction

XML (Extensible Markup Language) is a W3C standard used for easy interaction between Web applications and servers and data storage and use.

Data encoded using XML standards has the meaning and structure that can be easily interpreted by humans and computers. XML data is platform and application independent. Needless to say, this makes XML an ideal data exchange format suitable for the Internet (in fact, it was developed for this purpose ). Recently, the growth of broadband connections and consumer demand for applications that share data across any media means that XML Web Services and application software are becoming richer and richer.

XML was invented to solve the problem of describing the rich data on the Internet. So far, this problem can only be partially solved through the clever use of HTML.

The following is an example of an XML document:
Program code
Copy codeThe Code is as follows:
<? Xml version = "1.0"?>
<Party>
<Location> My House </location>
<Time> 7 </time>
<Guest>
<Name> John Bloggs </name>
<Item> Crate of Fosters </item>
</Guest>
<Guest>
<Name> Sara Bloggs </name>
<Item> Umbrella </item>
</Guest>
<Guest>
<Name> David Fig </name>
<Item> Bombay Mix </item>
</Guest>
</Party>

If you have never seen XML before, you can think it looks like HTML. HTML is a SGML application, and XML is a subset of it. However, their similarity also includes their similar annotation delimiters.

You only need to take a look at the XML snippet above. We can see that this data describes a party with some guests. Each guest corresponds to one. The label name used to describe the data is completely selected by the author. All XML standards require that the data must be consistent and the labels used to describe the data are constructed in a good structure. We can further use a document type declaration (DTD) or an XML schema to force data integrity. However, for simplicity, we will only use common XML in this article.

Ii. XML applications

Just now, we have seen how to use XML to describe data of any type. In fact, XML has been widely used in many Web applications today. Below are some well-known application descriptions:

· XHTML-this is one of the most widely used XML applications. It is similar to the HTML-based SGML-used to describe how data is displayed on a webpage. XHTML uses a DTD to ensure that all documents comply with standards. The emergence of XHTML makes Web programmer development a little easier. However, a web browser completely compatible with CSS and XHTML standards has not yet appeared.

XML-RPC-Remote Procedure Call (RPC), used in distributed applications to call processes on remote computers. The XML-RPC uses XML to encode information about a procedure call and sends it to the receiving computer using HTTP. Then, the returned value of the process is encoded in XML again and sent back to the caller's computer through an HTTP connection.

· RSS-truly simple aggregation/rich Site Summaries. It is a method used to aggregate website content (such as news, articles, shared prices and links, it uses a special application (A aggregator) to regularly update RSS feedback on the user's PC. The RSS data is encoded and transmitted using XML.

· AJAX-Asynchronous JavaScript and XML allow web developers to create event-driven web applications running on web browsers with rich features. JavaScript is used to send XML-encoded data to a server-side script (or receive XML-encoded data from the server ), and allows partial real-time page updates without updating all page content.

The above is only part of the possible application of XML. In future articles, we will analyze how to use these applications in PHP.

3. Use XML in PHP

Since PHP 5.0, the number of available options for PHP to interact with XML has increased significantly. PHP version 4 provides unstable and non-w3c compatible dom xml extensions.
Next, I will focus on three methods provided by PHP 5 that allow us to interact with XML: DOM, simple XML, and XPath. Where possible, I would suggest conditions and data that best suit each method. All the sample code uses an XML data source to describe a library and its contained books.

Program code
Copy codeThe Code is as follows:
<Xml version = "1.0"?>
<Library>
<Categories>
<Category cid = "1"> Web Development </category>
<Category cid = "2"> Database Programming </category>
<Category cid = "3"> PHP </category>
<Category cid = "4"> Java </category>
</Categories>
<Books>
<Book>
<Title> Apache 2 </title>
<Author> Peter Wainwright </author>
<Publisher> Wrox </publisher>
<Category> 1 </category>
</Book>
<Book>
<Title> Advanced PHP Programming </title>
<Author> George Schlossnagle </author>
<Publisher> Developer Library </publisher>
<Category> 1 </category>
<Category> 3 </category>
</Book>
<Book>
<Title> Visual FoxPro 6-Programmers Guide </title>
<Author> Eric Stroo </author>
<Publisher> Microsoft Press </publisher>
<Category> 2 </category>
</Book>
<Book>
<Title> Mastering Java 2 </title>
<Author> John zukoski </author>
<Publisher> Sybex </publisher>
<Category> 4 </category>
</Book>
</Books>
</Library>


Iv. DOM

The dom php extension allows you to use W3C DOM APIs to operate on XML documents. Before PHP 5 appeared, this was the only way PHP could access XML documents. If you use DOM in JavaScript, you will realize that these object models are almost the same.

Since DOM methods are copeat when traversing and operating XML documents, any DOM-compatible code has obvious advantages-it is compatible with APIs of any other object model that implements the same W3C compatibility.

In the following example code, we use DOM to display information about each book. First, we traverse the list directories and load their IDs and Corresponding names into an index array. Then, we will display a brief description of each book:

PHP:
Copy codeThe Code is as follows:
<? Php
/* Here we must specify the XML version: 1.0 */
$ Xml = new DomDocument ('1. 0 ');
$ Xml-> load ('xml/library. xml ');
/* First, create a directory list */
$ Categories = array ();
$ XMLCategories = $ xml-> getElementsByTagName ('category')-> item (0 );
Foreach ($ XMLCategories-> getElementsByTagName ('category') as $ categoryNode ){
/* Note how we get the attribute */
$ Cid = $ categoryNode-> getAttribute ('cid ');
$ Categories [$ cid] = $ categoryNode-> firstChild-> nodeValue;
}
?>
<Html>
<Head>
<Title> XML Library </title>
</Head>
<Body>
<?
Php foreach ($ xml-> getElementsBytagName ('book') as $ book ):
/* Search for titles */
$ Title = $ book-> getElementsByTagName ('title')-> item (0)-> firstChild-> nodeValue;
/* Find the author. For simplicity, assume that there is only one author */
$ Author = $ book-> getElementsByTagName ('author')-> item (0)-> firstChild-> nodeValue;
/* List Directory */
$ BookCategories = $ book-> getElementsByTagName ('category ');
$ CatList = '';
Foreach ($ bookCategories as $ category ){
$ CatList. = $ categories [$ category-> firstChild-> nodeValue]. ',';
}
$ CatList = substr ($ catList, 0,-2);?>
<Div>
<H2> <? Php echo ($ title)?> </H2>
<P> <B> Author: </B >:<? Php echo ($ author)?> </P>
<P> <B> Categories: </B >:<? Php echo ($ catList)?> </P>
</Div>
<? Php endforeach;?>
</Html>
[Html]
It is troublesome to modify XML. For example, the Code for adding a directory is as follows:

PHP:
[Code]
Function addCategory (DOMDocument $ xml, $ catID, $ catName ){
$ CatName = $ xml-> createTextNode ($ catName); // create a node to store text
$ Category = $ xml-> createElement ('category '); // create a directory Element
$ Category-> appendChild ($ catName); // Add the text to the directory element.
$ Category-> setAttribute ('cid', $ catID); // you can specify the directory ID.
$ XMLCategories = $ xml-> getElementsByTagName ('category')-> item (0 );
$ XMLCategories-> appendChild ($ category); // Add a new directory
}

 5. Save XML

You can use one of the save () and saveXML () Methods to convert the DOM description back to the XML string description. The save () method saves XML to a file with a specified name, while saveXML () returns a string from part or whole of the document.

$ Xml-> save ('xml/library. xml ');
// Save all objects
$ Categories = $ xml-> saveXML ($ XMLCategories );
// Returns a string containing a type.

To demonstrate how easy it is to port DOM-compatible code to another language, the following code is implemented in the form of JavaScript with the same functions as above:

Javascript:
Copy codeThe Code is as follows:
Function doXML (){
/* Create a category list first */
Var categories = Array ();
Var XMLCategories = xml. getElementsByTagName ('category') [0];
Var theCategories = XMLCategories. getElementsByTagName ('category ');
For (var I = 0; I <theCategories. length; I ++ ){
/* Pay attention to how we get the attribute */
Var cid = theCategories [I]. getAttribute ('cid ');
Categories [cid] = theCategories [I]. firstChild. nodeValue;
}
Var theBooks = xml. getElementsByTagName ('book ');
For (var I = 0; I <theBooks. length; I ++ ){
Var book = theBooks [I];
/* Search for titles */
Var title = book. getElementsByTagName ('title') [0]. firstChild. nodeValue;
/* Find the author. For simplicity, we assume that there is only one author */
Var author = book. getElementsByTagName ('author') [0]. firstChild. nodeValue;
/* List types */
Var bookCategories = book. getElementsByTagName ('category ');
Var catList = '';
For (var j = 0; j <bookCategories. length; j ++ ){
CatList + = categories [bookCategories [j]. firstChild. nodeValue] + ',';
}
CatList = catList. substring (0, catList. length-2 );
Document. open ();
Document. write ("Document. write ("<p> <B> Author: </B>:" + author + "</p> ");
Document. write ("<p> <B> Categories: </B>:" + catList + "</p> ");
}
Document. close ();
}

Vi. simple XML

Simple XML is indeed simple. It allows the use of object and array access methods to access an XML document and its elements and attributes. The operation is simple:

· Element-these are described as single attributes of SimpleXMLElement objects. When multiple child elements exist as documents or elements, each element can be accessed using an array index flag.

$ Xml-> books; // The returned element "books"
$ Xml-> books-> book [0]; // return the first book in the books element.

· Attribute-the Attribute of an element is accessed and set by associating the array flag. At this time, each index corresponds to a property name.

$ Category ['cid']; // return the cid Attribute Value

· Element Data-to retrieve text Data contained in an Element, you must use (string) explicitly converts it to a string or outputs it using print or echo. If an element contains multiple text nodes, they are connected in the order found.

Echo ($ xml-> books-> book [0]-> title); // displays the title of the first book.

The following is an example of conversion using simple XML. To load an XML file, we use the simplexml_load_file () function to analyze the XML file and load it into a SimpleXMLElement object:

PHP:
Copy codeThe Code is as follows:
<? Php
$ Xml = simplexml_load_file ('xml/library. xml ');
/* Load a List Directory into an array */
$ Categories = array ();
Foreach ($ xml-> categories-> category as $ category ){
$ Categories [(string) $ category ['cid'] = (string) $ category;
}
?>
<Html>
<Head>
<Title> XML Library </title>
</Head>
<Body>
<? Php foreach ($ xml-> books-> book as $ book ):
/* List directories */
$ CatList = '';
Foreach ($ book-> category as $ category ){
$ CatList. = $ categories [(string) $ category)]. ',';
}
$ CatList = substr ($ catList, 0,-2);?>
<Div>
<H2> <? Php echo ($ book-> title)?> </H2>
<P> <B> Author: </B >:<? Php echo ($ book-> author)?> </P>
<P> <B> Categories: </B >:<? Php echo ($ catList)?> </P>
</Div>
<? Php endforeach;?>
</Html>


7. Modify XML

Although text data and attribute values can be set using simple XML, these objects cannot be created. However, SimpleXM does provide a way to convert between a DomElement object and a DomElement object. To this end, I modified the addCategory () function to demonstrate how to use the simplexml_import_dom () function to add a directory and convert the document back to a simple XML format:

PHP:
Copy codeThe Code is as follows:
Function addCategory (SimpleXMLElement & $ sXML, $ catID, $ catName ){
$ Xml = new DOMDocument;
$ Xml-> loadXML ($ sXML-> asXML ());
$ CatName = $ xml-> createTextNode ($ catName); // create a node to store the text
$ Category = $ xml-> createElement ('category '); // create a directory Element
$ Category-> appendChild ($ catName); // Add text to the directory Element
$ Category-> setAttribute ('cid', $ catID); // you can specify a directory id.
$ XMLCategories = $ xml-> getElementsByTagName ('category')-> item (0 );
$ XMLCategories-> appendChild ($ category); // Add a new directory
$ SXML = simplexml_import_dom ($ xml );
Return $ sXML;
}

Similarly, the asXML () function of the SimpleXMLElement object can be used to retrieve the XML string and save it back to a file.

8. xPath

There is no doubt that Xpath is "cherries on the XML cake ". XPath allows you to use SQL-like queries to find specific information in an XML document. DOM and SimpleXML both have built-in support for XPath, such as SQL, which can be used to extract anything you want from an XML document.

Program code
· // Category-find all the category that appears in the document.

·/Library/books-find all books that appear as library children

·/Library/categories/category [@ cid]-search for all the category attributes that appear as cid for the children of library/categories.

·/Library/categories/category [@ att = '2']-search for the category that appears when the value of the attribute cid of all children serving as library/categories is 2.

·/Library/books/book [title = 'apache 2']-search for all children whose names are/library/books and whose title element has a book whose value is Apache 2.

In fact, this is only the tip of the xPath iceberg. You can use xPath to create a large number of complex queries to extract almost any information from your documents. I modified the sample code again to show you how easy it is to use xPath.

PHP:
Copy codeThe Code is as follows:
<? Php
$ Xml = simplexml_load_file ('xml/library. xml ');
?>
<Html>
<Head>
<Title> XML Library </title>
</Head>
<Body>
<? Php foreach (array) $ xml-> xpath ("/library/books/book") as $ book ):
/* List Directory */
$ CatList = '';
Foreach ($ book-> category as $ category ){
/* Get the directory with this ID */
$ Category = $ xml-> xpath ("/library/categories/category [@ cid = '$ category']");
$ CatList. = (string) $ category [0]. ',';
}
$ CatList = substr ($ catList, 0,-2);?>
<Div>
<H2> <? Php echo ($ book-> title)?> </H2>
<P> <B> Author: </B >:<? Php echo ($ book-> author)?> </P>
<P> <B> Categories: </B >:<? Php echo ($ catList)?> </P>
</Div>
<? Php endforeach;?>
</Html>

  9. DOM and XPath

To compute the XPath query in the DOM, you need to create a DOMXPath object. The following evaluate () function returns a DOMElement array.
Copy codeThe Code is as follows:
$ XPath = new DOMXPath ($ xml );
$ XPath-> evaluate ("/library/books/book [title = 'apache 2']");

Conclusion

Now we have learned how to use the tools provided by PHP to interact with XML. So far, we have been "armed" and are ready to delve into XML applications. In the next article, we will discuss AJAX and how it is applied to website development such as Google.

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.