How to add XML document content through PHP _php tips

Source: Internet
Author: User

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.

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.