Home > Article > Backend Development > Using DOM to control XML_PHP tutorial in PHP5
php(as the current mainstream development language)5 has enhanced support for xml(standardization is getting closer), and uses DOM to extend xml( Standardization is getting closer)Ability to operate. These functions are part of the core of php(as the current mainstream development language)5 and can be used without installation.
The following example simply demonstrates the operation of DOM on xml(standardization is getting closer). For detailed explanation, please see the comments in the code
/**************************************************
* * use xml(standardization is getting closer) in php(as the current mainstream development language)5
** reference site:
** http: //cn.php(as the current mainstream development language).net/manual/zh/ref.dom.php(as the current mainstream development language)
** the follow codes need php(as the current mainstream development language)5 support
************************ **************************/
//First create a DOMDocument object
$dom = new DomDocument();
//Then load xml(Standardization is getting closer)File
$dom -> load("test.xml(Standardization is getting closer)");
/ /Output xml(Standardization is getting closer)File
//header("Content-type: text/xml(Standardization is getting closer);charset= gb2312");
//echo $dom -> savexml(Standardization is getting closer)();
//Save xml(Standardization is getting closer) Close) file, the return value is int (file size in bytes)
//$dom -> save("newfile.xml(Standardization is getting closer)");
echo "
/*
echo "
$xpath = new domxpath($dom);
$titles = $xpath->query("/rss/channel/item/title");
foreach ($titles as $node)
{
echo $node->textContent."
";
}
/*
This is similar to using the getElementsByTagName() method , but Xpath is much more powerful
A deeper look may be like this:
/rss/channel/item[position() = 1]/title returns all the first item element
/rss/channel/ item/title[@id = 23] Returns all titles containing the id attribute and the value is 23
/rss/channel/&folder&/title Returns all titles under the articles element (Translator's Note: &folder& represents directory depth)
*/
$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 node from DOM
//Or use xpath to query the node and delete it
//$dom->documentElement-> RemoveChild($xpath->query("/rss/channel")->item(0));
//$dom->save("newfile.xml
(Standardization is getting closer)
");//Modify node data from DOM
//This place is stupid, create a new node, and then replace the old one node. If anyone has other good methods, please tell me