search
HomeBackend DevelopmentPHP TutorialBasics 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

Copy code The code is as follows:



My House


 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: :



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:
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 /* 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 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 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();
}

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

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:
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
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.
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...
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.