Home >Backend Development >PHP Tutorial >Implementation code for parsing php DOMElement and manipulating xml documents_PHP tutorial
$itemsNodeList = $xmldoc->getElementsbyTagName('Student');
$itemElement = $itemsNodeList->item(0);//Get the first complete student information node
$itemChildsNodeList = $itemElement->getElementsbyTagName('name');//Get the child node "name", there may be multiple names
$itemChildNode = $itemChildsNodeList->item(0);//Get the first name Node
echo $itemChildNode->nodeValue;//Output node value
//Encapsulated into a function
$nodeArr = array('name', 'age', 'introduction');
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, 'Student', $nodeArr);
print_r($data);
//Delete node
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$student = $xmldoc->getElementsByTagName('Student')->item(2);//Directly find the node to be deleted
$student->parentNode->removeChild($student);//The parent node’s Delete method
$xmldoc->save('datas.xml');
//Modify node value
$student = $xmldoc->getElementsByTagName('student')->item(2);
$student->getElementsByTagName('age')-> item(0)->nodeValue += 10;
$student->setAttribute('id', '110');
$xmldoc->save('datas.xml');
//Apply Xpath to find nodes
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->load('dat.xml');
$xpath = new DOMXPath($xml);
$nodeList = $xpath->query('/aaa/bbb/ddd/fff');
echo $nodeList->item(0)->nodeValue;
//SimpleXML class operation xml
/*1001
< ;title>Tian Long Ba Bu1002
< price>321 yuan
< ;book house="People's Publishing House">1004
*/
$xml = simplexml_load_file('books.xml');
$books = $xml->book;
echo $books[1]->title . $books[1]['house'];//directly points to the second book
foreach( $xml as $item){
echo $item->title,' ',$item['house'],'
';
}