这个是index.xml
<?xml version="1.0" encoding="utf-8"?>
<!--保存编码utf-8-->
<!--引入dtd-->
<!DOCTYPE 班级 SYSTEM "class01.dtd">
<班级>
<学生>
<名字>周星驰</名字>
<年龄>23</年龄>
<介绍>学习刻苦</介绍>
</学生>
<学生>
<名字>杨钰莹</名字>
<年龄>27</年龄>
<介绍>唱歌好听</介绍>
</学生>
</班级>
class01.dtd是用来限制xml的,会看就可以
<!ELEMENT 班级 (学生+)>
<!ELEMENT 学生 (名字,年龄,介绍)>
<!ELEMENT 名字 (#PCDATA)>
<!ELEMENT 年龄 (#PCDATA)>
<!ELEMENT 介绍 (#PCDATA)>
read.php用来查看节点
<html>
<?php
$xmldoc=new DOMDocument();
$xmldoc->load("index.xml");
//var_dump($xmldoc);查看方法属性
$stus=$xmldoc->getElementsByTagName("学生");
echo "共有".$stus->length;
//选中第一个学生
$stu1=$stus->item(1);
//取出名字
// $stu_names=$stu1->getElementsByTagName("名字");
//echo $stu_names->item(0)->nodeValue;
echo getNodeVal($stu1,"年龄");
function getNodeVal(&$Mynode,$tagName){
return $Mynode->getElementsByTagName($tagName)->item(0)->nodeValue;
}
另外这个checkDtd.html是检查xml的正确性,但是只能IE打开支持。
<html><head>
<tilte>检验dtd</tilte>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
window.alert("你的");
//创建一个xml解析器,只能用IE浏览器
var xmldoc=new ActiveXObject("Microsoft.XMLDOM");
//开启校验功能
xmldoc.validateOnParse=true;
//指定对哪个xml文件校验
xmldoc.load("index.xml");
//如果有错误信息,则输出
document.write("</br>错误信息="+xmldoc.parseError.reason+"</br>");
document.write("错误的行号="+xmldoc.parseError.line+"</br>");
</script>
</head>
</html>
增加信息addDemo.php
<html>
<?php
//xml增删改
$xmldoc=new DOMDocument();
$xmldoc->load("index.xml");
//增加一个学生信息
//取出根节点
$root=$xmldoc->getElementsByTagName("班级")->item(0);
//创建学生节点和其他所有节点,子节点,创建出来是没有联系的
$stu_node=$xmldoc->createElement("学生");
//**********添加属性节点***********
$stu_node->setAttribute("性别","男");
//创建名字节点
$stu_node_name=$xmldoc->createElement("名字");
$stu_node_name->nodeValue="刘德华";
//把名字节点挂到学生节点下
$stu_node->appendChild($stu_node_name);
//创建年龄节点
$stu_node_age=$xmldoc->createElement("年龄");
$stu_node_age->nodeValue="33";
$stu_node->appendChild($stu_node_age);
//创建介绍节点
$stu_node_intro=$xmldoc->createElement("介绍");
$stu_node_intro->nodeValue="爱唱歌";
$stu_node->appendChild($stu_node_intro);
//把学生挂到跟节点下
$root->appendChild($stu_node);
//重新保存
$xmldoc->save("index.xml");
echo "增加完成,保存成功";
?>
</html>
删除一个信息delDemo.php
<html>
<?php
//xml增删改
$xmldoc=new DOMDocument();
$xmldoc->load("index.xml");
//删除一个学生信息
//取出根节点
$root=$xmldoc->getElementsByTagName("班级")->item(0);
//假设删除第三个学生
//1,找到该学生
$stus=$xmldoc->getElementsByTagName("学生");
$stu1=$stus->item(2);
//2,删除学生
//$root->removeChild($stu1);
//2,更灵活的方法,连root都不需要
$stu1->parentNode->removeChild($stu1);
$xmldoc->save("index.xml");
echo "删除完成,保存成功";
?>
</html>
修改一个信息updataDemo.php
<html>
<?php
//xml增删改
$xmldoc=new DOMDocument();
$xmldoc->load("index.xml");
//更改学生的年龄
$stus=$xmldoc->getElementsByTagName("学生");
$stu1=$stus->item(0);
$stu1_age=$stu1->getElementsByTagName("年龄")->item(0);
$stu1_age->nodeValue+=10;
$xmldoc->save("index.xml");
echo "更新完成,保存成功";
?>
“`