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>
노드 삭제:
<?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 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.