The XML support is enhanced in PHP5, and the XML operation capability is extended using DOM. These functions are part of the PHP5 core and can be used without installation.
The following example demonstrates DOM operations on XML. For more information, see the comments in the code.
<?
/*************************************** *********
** Use XML in PHP5
** Reference site:
** Http://cn.php.net/manual/zh/ref.dom.php
** The follow codes need PHP5 support
**************************************** *********/
// Create a DOMDocument object first
$ Dom = new DomDocument ();
// Load the XML file
$ Dom-> load ("test. xml ");
// Output the XML file
// Header ("Content-type: text/xml; charset = gb2312 ");
// Echo $ dom-> saveXML ();
// Save the XML file. The returned value is int (file size, in bytes)
// $ Dom-> save ("newfile. xml ");
Echo "$ Titles = $ dom-> getElementsByTagName ("title ");
Foreach ($ titles as $ node)
{
Echo $ node-> textContent. "<br/> ";
// You can also
// Echo $ node-> firstChild-> data. "<br/> ";
}
/*
Echo "Foreach ($ dom-> documentElement-> childNodes as $ items ){
// If the node is an element (nodeType = 1) and its name is item, the loop continues.
If ($ items-> nodeType = 1 & $ items-> nodeName = "item "){
Foreach ($ items-> childNodes as $ titles ){
// If a node is an element and its name is title, print it.
If ($ titles-> nodeType = 1 & $ titles-> nodeName = "title "){
Print $ titles-> textContent. "n ";
}
}
}
}
*/
// Use XPath to query data
Echo "$ Xpath = new domxpath ($ dom );
$ Titles = $ xpath-> query ("/rss/channel/item/title ");
Foreach ($ titles as $ node)
{
Echo $ node-> textContent. "<br/> ";
}
/*
This is similar to using the getElementsByTagName () method, but Xpath is much more powerful.
In depth, it may be like this:
/Rss/channel/item [position () = 1]/title returns all
/Rss/channel/item/title [@ id = '23'] return all the titles that contain the id attribute and whose value is 23.
/Rss/channel/& folder &/title returns the title under all articles elements)
*/
// Write new data to the DOM
$ Item = $ dom-> createElement ("item ");
$ Title = $ dom-> createElement ("title ");
$ TitleText = $ dom-> createTextNode ("title text ");
$ Title-> appendChild ($ titleText );
$ Item-> appendChild ($ title );
$ Dom-> documentElement-> getElementsByTagName ('channel')-> item (0)-> appendChild ($ item );
// Delete a node from the DOM
// $ Dom-> documentElement-> RemoveChild ($ dom-> documentElement-> getElementsByTagName ("channel")-> item (0 ));
// Alternatively, use xpath to query the nodes and then delete them.