php DOMElement operation xml document demonstration

  • 2020-05-30 19:43:26
  • OfStack

 
<?php 
//Store your html into $html variable. 
$html="<html> 
<head> 
<title>Rakesh Verma</title> 
</head> 
<body> 
<a href='http://example.com'>Example</a> 
<a href='http://google.com'>Google</a> 
<a href='http://www.yahoo.com'>Yahoo</a> 
</body> 
</html>"; 
$dom = new DOMDocument(); 
$dom->loadHTML($html); 
//Evaluate Anchor tag in HTML 
$xpath = new DOMXPath($dom); 
$hrefs = $xpath->evaluate("/html/body//a"); 
for ($i = 0; $i < $hrefs->length; $i++) { 
$href = $hrefs->item($i); 
$url = $href->getAttribute('href'); 
//remove and set target attribute 
$href->removeAttribute('target'); 
$href->setAttribute("target", "_blank"); 
$newURL=$url.".au"; 
//remove and set href attribute 
$href->removeAttribute('href'); 
$href->setAttribute("href", $newURL); 
} 
// save html 
$html=$dom->saveHTML(); 
echo $html; 
?> 

Case 2
 
/*<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<!-- css Style definition without a dot. Such as: name{color:red;} --> 
<?xml-stylesheet type="text/css" href="css.css"?> 
<!--  The introduction of dtd Document definition file   (root element: class) <!DOCTYPE  The class  SYSTEM "class.dtd" /> --> 
<!-- <!DOCTYPE  The class [ 
<!ELEMENT  The class  ( students +)> 
<!ELEMENT  students  ( The name , age , introduce )> 
<!ELEMENT  The name  (#PCDATA)> 
<!ELEMENT  age  (#PCDATA)> 
<!ELEMENT  introduce  (#PCDATA)> 
] /> --> 
< The class > 
< students  number="101"> 
< The name > The Monkey King </ The name > 
< The name > Sun walkers </ The name > 
< age >123</ age > 
< introduce ><![CDATA[&*$% Special string ^&#$&]]></ introduce > 
</ students > 
< students  number="10&quot;2"> 
< The name > Bones jing </ The name > 
< age >140</ age > 
< introduce > Introduce the content </ introduce > 
</ students > 
</ The class > 
*/ 
$xmldoc = new DOMDocument('1.0', 'UTF-8'); 
$xmldoc->load('datas.xml'); 
$itemsNodeList = $xmldoc->getElementsbyTagName(' students '); 
$itemElement = $itemsNodeList->item(0);// Get the first 1 A complete student information node  
$itemChildsNodeList = $itemElement->getElementsbyTagName(' The name ');// Get a child node "name", perhaps with more than one name  
$itemChildNode = $itemChildsNodeList->item(0);// Get the first 1 Name node  
echo $itemChildNode->nodeValue;// Output node value  
// Encapsulated as a function  
$nodeArr = array(' The name ', ' age ', ' introduce '); 
function getNodeVal($xmldoc, $itemsName, $nodeArr){ 
$items = $xmldoc->getElementsByTagName($itemsName); 
for($i=0; $i < $items->length; $i++){ 
$item = $items->item($i); 
foreach($nodeArr as $node){ 
$data[$i][] = $item->getElementsByTagName($node)->item(0)->nodeValue; 
} 
} 
return $data; 
} 
$data = getNodeVal($xmldoc, ' students ', $nodeArr); 
print_r($data); 

Related articles: