This example describes how to delete the contents of an XML document through PHP. Share to everyone for your reference. The implementation methods are as follows:
In the first case: delete a student node
Copy Code code as follows:
<?php
1, create a DOMDocument object. The object represents an XML file
$xmldoc = new DOMDocument ();
2. Load XML file (specify which XML file to parse, at which point the DOM tree node will be loaded into memory)
$xmldoc->load ("Class.xml");
3, delete a student student information record
(1) Remove the root node
$root = $xmldoc->getelementsbytagname ("Class")->item (0);//Not when deleted by node, this code does not need
(2) Find the student
$stu = $xmldoc->getelementsbytagname ("student");
$stu _del = $stu->item (2);/Find a third student
$root->removechild ($stu _del);//delete operation, this is method 1
$stu _del->parentnode->removechild ($stu _del);//Find its parent node, the parent node performs the delete operation, this is method 2
4. Update XML document
$xmldoc->save ("Class.xml");
echo "Delete Success";
?>
Second: Delete One of the nodes under the student node, such as age:
Copy Code code as follows:
<?php
1, create a DOMDocument object. The object represents an XML file
$xmldoc = new DOMDocument ();
2. Load XML file (specify which XML file to parse, at which point the DOM tree node will be loaded into memory)
$xmldoc->load ("Class.xml");
3, delete a student student information record
(1) Remove the root node
$root = $xmldoc->getelementsbytagname ("Class")->item (0);
(2) Find the student
$stu = $xmldoc->getelementsbytagname ("Age");
$stu _del = $stu->item (1);//Find The age of the second student
$stu _del->parentnode->removechild ($stu _del);//delete operation
4. Update XML document
$xmldoc->save ("Class.xml");
echo "Delete Success";
?>
I hope this article will help you with your PHP operating XML program.