This example describes how to add XML document content through PHP. Share to everyone for your reference. The specific analysis is as follows:
Here's how to add XML document content, from the previous "Dom Basics and PHP read XML content Operation Method" continues, the code is as follows:
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, add a student information
(1) To remove the node
$root = $xmldoc->getelementsbytagname ("Class")->item (0);//Return DomElement object type
Var_dump ($root);
(2) Create student node student
$stu _node = $xmldoc->createelement ("student");//Return DomElement object type
$stu _node->setattribute ("id", "Big Beauty");//Add attributes to the created node, if necessary
(3) Create name, gender, age, etc node name, sex
$stu _node_name = $xmldoc->createelement ("name");
$stu _node_name->nodevalue = "Big Joe";
$stu _node_sex = $xmldoc->createelement ("sex");
$stu _node_sex->nodevalue = "female";
$stu _node_age = $xmldoc->createelement ("Age");
$stu _node_age->nodevalue = "25";
(4) Mount name, sex, age, three nodes to the student node
$stu _node->appendchild ($stu _node_name);
$stu _node->appendchild ($stu _node_sex);
$stu _node->appendchild ($stu _node_age);
(5) Mount the student node on the root node
$root->appendchild ($stu _node);
4. Save to XML document
$xmldoc->save ("Class.xml");//saved to the original XML document, which is equivalent to add later; if it is a nonexistent XML document, a new XML document will be created with the original XML content + newly added content.
?>
I hope this article will help you with your PHP operating XML program.