The basic article of developing XML application in PHP Add node Delete node query node query section _php Tutorial

Source: Internet
Author: User
Tags php foreach
I. Introduction to XML

XML (Extensible Markup Language) is a standard that is used primarily for easy interaction between Web applications and servers, and for the storage and use of data.

Data encoded using XML standards has the meaning and structure that can be easily interpreted by people and computers. XML data is platform-and application-independent. Needless to say, this in itself makes XML an ideal data interchange format for the Internet (in fact, it was developed for this purpose). More recently, the growth of broadband connectivity and the need for consumer applications to share data across any media means that XML Web services and applications are becoming richer.

The invention of XML is to solve the organizational problem of describing the rich data on the Internet, so far, this problem can only be partially solved by the clever use of HTML.

The following is an example of an XML document:
Program code
Copy CodeThe code is as follows:


  My House
  7pm
 
   John Bloggs
   Crate of Fosters
 
 
   Sara Bloggs
   Umbrella
 
 
   David Fig
   Bombay Mix
 


If you haven't seen XML before, then you can think of it as HTML. HTML is an SGML application, and XML is a subset of it. However, their similarity also includes their similar label separators.

Just look at the XML fragment above, and we can see that the data describes a party with some guests, each of whom corresponds to one item. The label name used to describe the data is completely selected by the author. All XML standards require that the data be consistent and that the label used to describe the data is well-structured. We can further use a document type declaration (DTD) or an XML schema to enforce the integrity of the data. For the sake of simplicity, however, we will use only plain XML in this article.

Second, the XML application

Just now, we've seen how to use XML to describe any kind of data. In fact, XML has been widely used in many of today's web applications, and here are some notable application descriptions:

· Xhtml-This is one of the most widely used XML applications. It resembles HTML-based sgml-to describe how data is displayed on a Web page. XHTML uses a DTD to ensure that all documents conform to the standard. The advent of XHTML makes the development of web programmers a little easier; however, a Web browser that is fully compatible with CSS and XHTML standards has not yet appeared.

· xml-rpc-Remote Procedure Call (RPC), which is applied to a distributed application to invoke a procedure on a remote computer. XML-RPC uses XML to encode information about a procedure call and sends it to the receiving computer using HTTP. The return value of the procedure is then again encoded in XML and sent back to the caller's computer using an HTTP connection.

· Rss-is a truly simple aggregation/rich Site Summary, a method used to aggregate Web site content (such as news, articles, shared prices, and links), which periodically updates the RSS feeds on the user's PC with a special application (an aggregator). The RSS data is encoded and transmitted using XML.

· ajax-asynchronous JavaScript and XML, allowing Web developers to create rich-featured event-driven Web applications that run on Web browsers. JavaScript is used to send XML-encoded data to server-side scripts (or to receive XML-encoded data from the server side) and to allow local, real-time page updates without the need to update 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.

third, using XML in PHP

The available options for PHP interaction with XML have increased significantly since PHP 5.0. PHP version 4 provides an unstable and non-compliant DOM XML extension.
Below, I'll focus on the three methods PHP 5 provides to us that allow us to interact with XML: DOM, simple XML, and XPath. Where possible, I will recommend the conditions and data that are most appropriate for each method. All of the sample code uses an XML data source to describe a library and the books it contains.

Program code
Copy CodeThe code is as follows:


 
   Web Development
   Database programming
   Php
   Java
 
 
 
   Apache 2
Peter Wainwright
   Wrox
   1
 
 
   Advanced PHP Programming
George Schlossnagle
   Developer Library
   1
   3
 
 
   Visual FoxPro 6-programmers Guide
Eric Stroo
   Microsoft Press
   2
 
 
   Mastering Java 2
John Zukowski
   Sybex
   4
 




Iv. DOM

Dom PHP extensions allow the use of the world's Dom API to operate on XML documents. Before PHP 5 appeared, this was the only way PHP could access XML documents. If you use the DOM in JavaScript, you will realize that these object models are almost identical.

Because DOM methods are verbose when traversing and manipulating XML documents, any DOM-compatible code has obvious advantages-compatible with any other API that implements the same model of a compatible object.

In the example code below, we use the DOM to display information about each book. First, we walk through the list of directories, loading their IDs and their corresponding names into an indexed array. We then display a short description of each book:

Php:
Copy CodeThe code is as follows:
/* 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 (' categories ')->item (0);
foreach ($XMLCategories->getelementsbytagname (' category ') as $categoryNode) {
/* Notice how we get the attributes */
$cid = $categoryNode->getattribute (' CID ');
$categories [$cid] = $categoryNode->firstchild->nodevalue;
}
?>


<title>XML Library</title>


PHP foreach ($xml->getelementsbytagname (' book ') as $book):
/* Find Title */
$title = $book->getelementsbytagname (' title ')->item (0)->firstchild->nodevalue;
/* Find authors-for simplicity, we 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);?>


Author::


Categories: :





[HTML]
To put it another way, it is more cumbersome to modify XML. For example, add a directory with the following code:

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 text to a catalog element
$category->setattribute (' CID ', $catID); Set the ID of the directory
$XMLCategories = $xml->getelementsbytagname (' categories ')->item (0);
$XMLCategories->appendchild ($category); Add a new directory
}

  v. Saving 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 the XML to a file with a specified name, and SaveXML () returns a string from part or whole of the document.

$xml->save (' xml/library.xml ');
Save All Files
$categories = $xml->savexml ($XMLCategories);
Returns a string containing the kind

To illustrate how easy it is to port the DOM-compatible code to another language, here's the same code that was implemented in JavaScript in the same way:

Javascript:
Copy CodeThe code is as follows:
function Doxml () {
/* First create a list of categories */
var categories = Array ();
var xmlcategories = xml.getelementsbytagname (' categories ') [0];
var thecategories = xmlcategories.getelementsbytagname (' category ');
for (var i = 0; i < thecategories.length; i++) {
/* Notice how we get the properties of */
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];
/* Find Title */
var title = Book.getelementsbytagname (' title ') [0].firstchild.nodevalue;
/* Find authors-for simplicity, we assume that there is only one author */
var author = book.getelementsbytagname (' author ') [0].firstchild.nodevalue;
/* List Type */
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 ("

"+ title +"

");
document.write ("

Author:: "+ Author +"

");
document.write ("

Categories: : "+ catlist +"

");
}
Document.close ();
}

VI. Simple XML

Simple XML is really simple. It allows the use of object and array access methods to access an XML document and its elements and attributes. The way to operate it is simple:

· Element-These are described as individual properties of the SimpleXMLElement object. When there are multiple child elements that exist as documents or elements, each element can be accessed using the array index flags.

$xml->books;//Returns the element "books"
$xml->books->book[0];//Returns the first book in the books element

· Property (Attribute)-the attribute of an element is accessed and set by an associative array flag, at which point each index corresponds to a property name.

$category [' CID '];//returns the value of the Cid property

· element data-In order to retrieve text data contained within an element, you must explicitly convert it to a string using (string) or output it using print or echo. If an element contains multiple text nodes, they are concatenated in the order in which they are found.

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

The following is the original instance of converting using simple XML. To load the XML file, we use the simplexml_load_file () function, which parses the XML file and loads it into a SimpleXMLElement object:

Php:
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Xml/library.xml ');
/* Load a list of directories into an array */
$categories = Array ();
foreach ($xml->categories->category as $category) {
$categories [(String) $category [' cid ']] = (string) $category;
}
?>


<title>XML Library</title>


Books->book as $book):
/* List Directory */
$catList = ";
foreach ($book->category as $category) {
$catList. = $categories [((String) $category)]. ', ';
}
$catList = substr ($catList, 0,-2);?>

title)?>


Author:: Author)?>


Categories: :







Vii. Modifying XML

Although text data and property values can be set by using simple XML, these objects cannot be created. However, SIMPLEXM does provide a way to implement transformations between DomElement objects and DomElement objects. To do this, I modified the addcategory () function to illustrate 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 hold the text
$category = $xml->createelement (' category '); Create a directory element
$category->appendchild ($catName); Add text to a catalog element
$category->setattribute (' CID ', $catID); Set Directory ID
$XMLCategories = $xml->getelementsbytagname (' categories ')->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 an XML string and save it back to a file.

Eight, XPath

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

Program code
· category-find any category that appears in the document.

· /library/books-Find all the books that appear as children of the Library

· /library/categories/category[@cid-Find all the category that appears as a library/categories child with the attribute CID.

· /library/categories/category[@att = ' 2 '-finds all children with Library/categories and has an attribute CID with a value of 2 appearing category.

· /library/books/book[title= ' Apache 2 '-Find all children as/library/books and its title element has a book with a value of Apache 2 appearing.

In fact, this is just one corner of the XPath iceberg. You can use XPath to create a large number of complex queries to extract almost any information from your document. I've changed the sample code again to show you how easy it is to use XPath.

Php:
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Xml/library.xml ');
?>


<title>XML Library</title>


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);?>

title)?>


Author:: Author)?>


Categories: :






   Nine, Dom and XPath

Evaluating an XPath query in the DOM requires creating an Domxpath object, and the following evaluate () function returns an DomElement array.
Copy CodeThe code is as follows:
$xPath = new Domxpath ($xml);
$xPath->evaluate ("/library/books/book[title= ' Apache 2 ']");

10. Conclusion

Now, we've learned how to use the tools that PHP provides to us to interact with XML. So far, we've been "armed" and ready to delve into the XML application. In the next article, we'll discuss Ajax and how it can be applied to sites like Google.

http://www.bkjia.com/PHPjc/322071.html www.bkjia.com true http://www.bkjia.com/PHPjc/322071.html techarticle XML Introduction XML (Extensible Markup Language) is a kind of standard, which is mainly used for easy interaction between Web application and server, storage and use of data. Use XML standard compilation ...

  • 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.