Home > php教程 > php手册 > body text

通过php添加xml文档内容的方法

WBOY
Release: 2016-06-13 09:16:29
Original
1216 people have browsed it

通过php添加xml文档内容的方法

 代码如下:

//1、创建一个DOMDocument对象。该对象就表示 xml文件
$xmldoc = new DOMDocument();
//2、加载xml文件(指定要解析哪个xml文件,此时dom树节点就会加载到内存中)
$xmldoc->load("class.xml");
//3、添加一条学生信息
//(1)取出要节点
$root = $xmldoc->getElementsByTagName("class")->item(0);//返回DOMElement对象类型
var_dump($root);
//(2)创建学生节点 student
$stu_node = $xmldoc->createElement("student");//返回DOMElement对象类型
$stu_node->setAttribute("id","大美女");//给创建的节点添加属性,如果有需要的话
//(3)创建名字、性别、年龄等节点 name、sex和age
$stu_node_name = $xmldoc->createElement("name");
$stu_node_name->nodeValue = "大乔";
$stu_node_sex = $xmldoc->createElement("sex");
$stu_node_sex->nodeValue = "女";
$stu_node_age = $xmldoc->createElement("age");
$stu_node_age->nodeValue = "25";
//(4)将name、sex、age等三个节点挂载到student节点上
$stu_node->appendchild($stu_node_name);
$stu_node->appendchild($stu_node_sex);
$stu_node->appendchild($stu_node_age);
//(5)把student节点挂载到根节点上
$root->appendchild($stu_node);
//4、保存到 xml 文档中
//$xmldoc->save("class.xml");//保存到原xml文档中,相当于在后面添加;如果是一个不存在的xml文档,则会新建一个xml文档,内容为原xml内容+新添加的内容。
?>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!