php原生开发中对xml文件的增删改操作
【代码】php原生开发中对xml文件的增删改操作。
·
1.php原生开发中对xml文件的增删改操作
<?php
$path = 'note1.xml'; // xml文件的路径
// 查询文件是否存在,如何存在提示信息,不存在时创建该xml文件
if(file_exists($path)){
echo('文件已存在,请删除后新增');
return false;
}else{
// 创建新的xml 文件
// 创建一个XML文档
$doc = new DOMDocument('1.0','UTF-8');
// 添加根元素
$root = $doc->createElement('parent');
$doc->appendChild($root);
// 添加子元素和属性
$child = $doc->createElement('child');
$child->setAttribute('name', 'John');
// $child->appendChild($doc->createTextNode('Hello, World!'));
$root->appendChild($child);
// 给子元素添加新的元素与属性
$sex = $doc->createElement('sex');
$sex->setAttribute('sex', '男');
$child->appendChild($sex);
// 添加子元素和属性
$children = $doc->createElement('children');
$children->setAttribute('name', 'zhangsan');
// $children->appendChild($doc->createTextNode('你好,张三!'));
$root->appendChild($children);
$sex = $doc->createElement('sex');
$sex->setAttribute('sex', '男');
$children->appendChild($sex);
// 保存XML文件
$doc->formatOutput = true;
$doc->save('example.xml');
$localPath = 'example.xml';
}
// 对xml文件中的数据进行修改操作
$doc->load('example.xml');
$childrens = $doc->getElementsByTagName("children"); // 遍历数据
foreach($childrens as $children) {
if($children->getAttribute('name') == 'zhangsan') {
echo $children->getElementsByTagName("sex")->item(0)->nodeValue="女";
}
}
$doc -> save('example.xml');
// 删除操作
$childrens = $doc -> getElementsByTagName("children"); //遍历
foreach ($childrens as $children) { //将id=4的删除
if($children->getAttribute('sex')=='女'){
$root->removeChild($children);
}
} //对文件做修改后,一定要记得重新sava一下,才能修改掉原文件
$doc -> save('example.xml');
?>
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)