php DOMDocument应用实例(XML创建、添加、删除、修改)

发布时间:2020-02-09编辑:脚本学堂
php DOMDocument的用法,主要介绍使用DOMDocument进行xml文件的几个操作,供大家学习参考。

复制代码 代码示例:
<?php
$xmlpatch = 'index.xml';
$_id = '2';
$_title = 'has been changed';
$_content = 'has been changed';
$doc = new DOMDocument();
$doc -> formatOutput = true;
if($doc -> load($xmlpatch)) {
$root = $doc -> documentElement;
$elm = $root -> getElementsByTagName_r('index');
$checkexist = 0;
foreach ($elm as $new) {
   if($new -> getAttribute('id') == $_id) {
    $new -> setAttribute('title', $_title);
    $new -> nodeValue = $_content;//修改节点值
    //$new -> removeChild($new -> nodevalue);
    $checkexist = 1;
   }
}
if($checkexist == 0) {
   echo $_id . ' is not found in ' . $xmlpatch;
} else {
   $doc -> save($xmlpatch);
   echo $_id . ' has been changed';
}
} else {
echo 'xml file loaded error!';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>XML操作-修改</title>
</head>
<body>
</body>
</html>

4、del.php 删除功能
 

复制代码 代码示例:
<?php
$xmlpatch = 'index.xml';
$_id = '2';
$doc = new DOMDocument();
$doc -> formatOutput = true;
if($doc -> load($xmlpatch)) {
$root = $doc -> documentElement;
$elm = $root -> getElementsByTagName_r('index');
foreach ($elm as $new) {
   if($new -> getAttribute('id') == $_id) {
    if($root -> removeChild($new)) {
     echo $_id . ' has been deleted';
    } else {
     echo $_id . ' delete failed';
    }
   }
}
$doc -> save($xmlpatch);
} else {
echo 'xml file loaded error!';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>XML操作-删除</title>
</head>
<body>
</body>
</html>
 

 
总结:
创建跟添加主要用的就是create跟appendChild,create后边跟Element就是创建节点,跟Attribute就 是创建属性,TextNode就是创建值,然后appendChild就是设置从属关系。
删除与修改都是用先获得节点列表getElementsByTagName然后foreach遍历想要修改的节点,数据多可能会慢点。