Rumah > Artikel > pembangunan bahagian belakang > php 读写 xml
读取xml信息
test.xml
<?xml version="1.0" encoding="UTF-8"?> <class> <student> <name>张三</name> <age>23</age> <intro>努力学习</intro> </student> <student> <name>李四</name> <age>23</age> <intro>努力学习</intro> </student> </class>test.php
<?php $xmldoc = new DOMDocument(); $xmldoc->load("test.xml"); $stus = $xmldoc->getElementsByTagName("student"); for($i=0;$i length;$i++){ $stu = $stus->item($i); echo getNodeVal($stu,"name")."--".getNodeVal($stu,"age")."--". getNodeVal($stu,"intro")."<br>"; } function getNodeVal(&$MyNode,$tagName){ return $MyNode->getElementsByTagName($tagName)->item(0)->nodeValue; } ?>
写xml:
<span style="font-size:18px;"><?php $xmldoc = new DOMDocument("1.0","utf-8"); $xmldoc->load("classes2.xml"); //添加一个学生信息 //创建学生结点 $root = $xmldoc->getElementsByTagName("class")->item(0); $stu_node = $xmldoc->createElement("student"); $stu_node->setAttribute("sex", "男"); //创建名字结点并且挂载到学生结点下 $stu_node_name=$xmldoc->createElement("name"); $stu_node_name->nodeValue = "唐唐"; $stu_node->appendChild($stu_node_name); $stu_node_age=$xmldoc->createElement("age"); $stu_node_age->nodeValue = "24"; $stu_node->appendChild($stu_node_age); $stu_node_intro=$xmldoc->createElement("intro"); $stu_node_intro->nodeValue = "我是唐唐,我一直很努力"; $stu_node->appendChild($stu_node_intro); //把学生结点挂载到根结点下 $root->appendChild($stu_node); $xmldoc->save("new.xml"); ?></span>
删除结点:
<?php $xmldoc = new DOMDocument("1.0","utf-8"); $xmldoc->load("test.xml"); //删除一个结点 $root = $xmldoc->getElementsByTagName("class")->item(0); $stus = $xmldoc->getElementsByTagName("student"); $stu1 = $stus->item(2); //$root->removeChild($stu1); $stu1->parentNode->removeChild($stu1); $xmldoc->save("test.xml"); ?>
<?php $xmldoc = new DOMDocument("1.0","utf-8"); $xmldoc->load("test.xml"); //删除一个结点 $root = $xmldoc->getElementsByTagName("class")->item(0); $stus = $xmldoc->getElementsByTagName("student"); $stu1 = $stus->item(0); $stu1_name = $stu1->getElementsByTagName("name")->item(0); $stu1_name->nodeValue = "唐唐改名了"; $xmldoc->save("test.xml"); ?>
以上就介绍了php 读写 xml,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。