


Basics of developing XML applications in PHP Add nodes Delete nodes Query nodes Query sections_PHP Tutorial
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
< guest>
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:
四、 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;
}
?>
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: :
php endforeach; ?>
[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:
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:
$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;
}
?>
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: : php echo($catList) ?>
php endforeach; ?>
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:
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:
$xml = simplexml_load_file('xml/library.xml');
?>
head>
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) ?> h2>
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.
$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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
