这篇文章主要介绍了php实现对xml的增删改查操作,结合具体案例形式分析了php针对xml格式文件的增删改查操作相关实现技巧,需要的朋友可以参考下
具体如下:
案例:
index.php
<?php
header("content-type:text/html;charset=utf-8");
$xmldom = new DOMDocument();
$xmldom->load("demo2.xml");
//查询学生信息
$stus = $xmldom->getElementsByTagName("学生");
for ($i=0;$i<$stus->length;$i++){
$stu = $stus->item($i);
getxmlnode($stu, "姓名");
getxmlnode($stu, "年龄");
getxmlnode($stu, "性别");
getxmlnode($stu, "介绍");
}
function getxmlnode(&$stu,$tagname){
echo $stuname = $stu->getElementsByTagName($tagname)->item(0)->nodeValue."<br/>";
}
//添加一个学生信息
//addxml($xmldom);
function addxml($xmldom){
$root = $xmldom->getElementsByTagName("班级")->item(0);
$ostus = $xmldom->createElement_x_x("学生");
//添加属性
$ostus->setAttribute("恋爱状况","热恋中");
//$ostus->nodeValue="\r\n";
$root->a($ostus);
$ostu_name = $xmldom->createElement_x_x("姓名");
$ostus->a($ostu_name);
$ostu_name->nodeValue="小娜";
$ostu_sex = $xmldom->createElement_x_x("性别");
$ostus->a($ostu_sex);
$ostu_sex->nodeValue="女";
$ostu_age = $xmldom->createElement_x_x("年龄");
$ostus->a($ostu_age);
$ostu_age->nodeValue="23";
$ostu_intro = $xmldom->createElement_x_x("介绍");
$ostus->a($ostu_intro);
$ostu_intro->nodeValue="高一美女";
$xmldom->save("demo2.xml");
}
//删除一个学生信息
//del_element($xmldom);
function del_element($xmldom){
$dstus = $xmldom->getElementsByTagName("学生");
$laststu = $dstus->item($dstus->length-1);
$laststu->parentNode->removeChild($laststu);
}
//修改一个学生信息
//update_element($xmldom);
function update_element($xmldom){
$ustus = $xmldom->getElementsByTagName("学生");
$ustu = $ustus->item(0);
$ustu_age = $ustu->getElementsByTagName("年龄")->item(0);
$ustu_age->nodeValue+=10;
}
//写会到文件中
$xmldom->save("demo2.xml");
?>立即学习“PHP免费学习笔记(深入)”;
demo2.xml
<?xml version="1.0" encoding="UTF-8"?> <班级> </班级>
立即学习“PHP免费学习笔记(深入)”;
相关推荐:
PHP基于面向对象mysqli扩展库增删改查操作工具类的方法
立即学习“PHP免费学习笔记(深入)”;
以上就是PHP实现对xml的增删改查操作的方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号