Ways to delete XML document content via PHP _php tips

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.