讀取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 < $stus->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>