Basics of developing XML applications in PHP Add nodes Delete nodes Query nodes Query sections_PHP Tutorial

WBOY
Release: 2016-07-21 15:36:39
Original
843 people have browsed it

1. Introduction to XML

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

Data encoded using the XML standard has meaning and structure that can be easily interpreted by humans and computers. XML data is platform and application independent. Needless to say, this in itself makes XML an ideal data exchange format for the Internet (in fact, it was developed for this very purpose). Recently, the growth of broadband connections and consumer demand for applications that share data across any medium mean that XML Web services and applications are becoming increasingly rich.

XML was invented to solve the organizational 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 code The code is as follows:



My House

< guest>
 John Bloggs
 Crate of Fosters ;Sara Bloggs
 Umbrella
Bombay Mix
Like HTML. HTML is a SGML application, and XML is a subset of it. However, the similarity also includes that they have similar label separators.

Just by looking at the XML fragment above, we can see that the data describes a party with a number of guests; each guest corresponds to an item. The label names used to describe the data are entirely chosen by the author. All XML standards require that the data must be consistent and the tags used to describe the data must be well-formed. We can further enforce data integrity using a document type declaration (DTD) or an XML schema. However, for simplicity, we will only use plain XML in this article.


2. XML Applications


Just now, we have seen how to use XML to describe any kind of data. In fact, XML has been widely used in many web applications today. Here are some famous application descriptions:

· XHTML - This is one of the most widely used XML applications. It is similar to SGML based on HTML - used to describe how data is displayed on a web page. XHTML uses a DTD to ensure that all documents adhere to the standard. The emergence of XHTML has made development slightly easier for Web programmers; however, a web browser that is fully compatible with the CSS and XHTML standards has not yet emerged.

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

· RSS - Really Simple Syndication/Rich Site Summary, it is a method used to aggregate web site content (such as news, articles, share prices and links, etc.) using a special application The program (an aggregator) regularly updates RSS feeds on the user's PC. This RSS data is encoded and transmitted using XML.
 · AJAX - Asynchronous JavaScript and XML that allows web developers to create feature-rich, event-driven web applications that run in a web browser. Among them, JavaScript is used to send XML-encoded data to server-side scripts (or receive XML-encoded data from the server-side), and allows partial real-time page updates without updating all page content.

The above are just some of the possible applications of XML. In future articles, we will analyze how to use these applications in PHP.


3. Using XML in PHP


Since PHP 5.0, the options available for PHP to interact with XML have increased significantly. What PHP version 4 can provide is an unstable and non-w3c compatible DOM XML extension.
Below, I will focus on the three methods provided by PHP 5 that allow us to interact with XML: DOM, simple XML and XPath. Where possible, I will suggest conditions and data that are most appropriate for each approach. All sample code will use an XML data source to describe a library and the books it contains.

Program code


Copy code
The 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
 





四、 DOM

  DOM PHP扩展名允许使用W3C DOM API在XML文档上进行操作。在PHP 5出现之前,这是PHP能存取XML文档的唯一方法。如果你在JavaScript中使用了DOM,那么会认识到这些对象模型几乎是一样的。

  由于DOM方法在遍历和操作XML文档时比较罗嗦,所以任何DOM兼容的代码都有明显的优点-与任何其它实现相同的W3C兼容的对象模型的API兼容。

  在下面的实例代码中,我们使用DOM来显示关于每本书的信息。首先,我们遍历一下列表目录,把它们的Id和相应的名字装载到一个索引数组中。然后,我们显示每本书的一个简短描述:

  PHP:
复制代码 代码如下:

/*Here we must specify the XML version: which is 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) {
 /*Note how we get the attributes*/
 $cid = $categoryNode->getAttribute('cid');
$categories[$cid] = $categoryNode->firstChild->nodeValue;
}
?>


XML Library


php foreach($xml- >getElementsBytagName('book') as $book):
/*Find title*/
$title = $book->getElementsByTagName('title')->item(0)->firstChild ->nodeValue;
/*Find the author - for simplicity, we assume 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]
 Just to mention again, Modifying XML is more troublesome. For example, the code to add 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 catalog element
$category->appendChild( $catName); //Add text to the catalog element
$category->setAttribute('cid', $catID); //Set the ID of the catalog
$XMLCategories = $xml->getElementsByTagName( 'categories')->item(0);
$XMLCategories->appendChild($category); //Add new directory
}

5. Save XML

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

$xml->save('xml/library.xml');
//Save all files
$categories=$xml->saveXML($XMLCategories);
//Return a string containing the category

To illustrate how easy it is to port DOM-compatible code to another language, here is the code that implements the same function as above in JavaScript:

Javascript:
Copy code The code is as follows:

function doXML(){
/* First create a category list*/
var categories = Array();
var XMLCategories = xml.getElementsByTagName('categories')[0] ;
var theCategories = XMLCategories.getElementsByTagName('category');
for (var i = 0; i < theCategories.length; i++) {
/* Note how we get the attributes*/
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 the title */
var title = book.getElementsByTagName('title')[0].firstChild.nodeValue;
 /* Find the author - for simplicity, we assume there is only one author*/
 var author = book.getElementsByTagName('author') [0].firstChild.nodeValue;
/* List categories*/
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("< p>Author:: " + author + "

");
 document.write("

Categories: : " + catList + "

");
 }
document.close();
}

6. 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 operation is simple:

· Element - These are described as individual properties of the SimpleXMLElement object. When multiple elements exist as children of a document or element, each element can be accessed using the array index flag.

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

 ·Attribute - The attributes of an element are accessed and set through associative array flags. At this time, each index corresponds to an attribute name.

$category['cid']; // Return the value of the cid attribute

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

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

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

PHP:
Copy Code The code is as follows:

$xml = simplexml_load_file('xml/library.xml');
/* Put a list of directories Load into an array*/
$categories = array();
foreach($xml->categories->category as $category) {
 $categories[(string) $category[' cid']] = (string) $category;
}
?>


XML Library


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

title) ?>< /h2>

Author:: author) ?>


Categories: :







7. Modify XML

Although text data and attribute values ​​can be set by using simple XML, these objects cannot be created. However, SimpleXM does provide a way to convert 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 catalog and convert the document back to simple XML format:

PHP:
Copy code The 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 catalog element
$category->appendChild($catName); //Add text to the 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;
}

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

8. xPath

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

Program code
· //category-Find all categories that appear in the document.

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

· /library/categories/category[@cid] - Find all books that appear as children of library/categories and have attributes is the category of cid.

· /library/categories/category[@att='2'] - Find all categories that appear as children of library/categories and have attribute cid with a value of 2.

· /library/books/book[title='Apache 2'] - Finds all occurrences of book that are children of /library/books and whose title element has a value of Apache 2.

In fact, this is just 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've modified the sample code again to show you how easy and enjoyable it is to use xPath.

PHP:
Copy code The code is as follows:

$xml = simplexml_load_file('xml/library.xml');
?>


XML Library


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


< ;b>Categories: :






 9. DOM and XPath

To calculate XPath query in DOM, you need to create a DOMXPath object, the following evaluate() function Returns an array of DOMElements.
Copy code The code is as follows:

$xPath = new DOMXPath($xml);
$xPath-> evaluate("/library/books/book[title='Apache 2']");

 10. Conclusion

Now, we have learned how to use the tools provided by PHP to interact with XML. At this point, we are "armed" and ready to delve into XML applications. In the next article, we will discuss AJAX and how it is used in site development like Google.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322071.htmlTechArticle1. Introduction to XML XML (Extensible Markup Language) is a W3C standard mainly used for Web applications Implement easy interaction, data storage and use with the server. Compiled using XML standards...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!