php中DOMDocument简单用法示例代码(XML创建、添加、删除、修改)
2024-05-04 22:08:14
供稿:网友
共分四个文件,分别是创建、增加、删除、修改四个功能,变量都是写死的,改一改用$_POST方式接收就可以用了
//index.php 创建功能
代码如下:
<?php
$xmlpatch = 'index.xml';
$_id = '1';
$_title = 'title1';
$_content = 'content1';
$_author = 'author1';
$_sendtime = 'time1';
$_htmlpatch = '1.html';
Vevb.com$doc = new DOMDocument('1.0', 'utf-8');
$doc -> formatOutput = true;
Vevb.com$root = $doc -> createElement('root');//新建节点
Vevb.com$index = $doc -> createElement('index');//新建节点
Vevb.com$url = $doc -> createAttribute('url');//新建属性
$patch = $doc -> createTextNode($_htmlpatch);//新建TEXT值
$url -> appendChild($patch);//将$patch文本设为$url属性的值
Vevb.com$id = $doc -> createAttribute('id');
$newsid = $doc -> createTextNode($_id);
$id -> appendChild($newsid);
Vevb.com$title = $doc -> createAttribute('title');
$newstitle = $doc -> createTextNode($_title);
$title -> appendChild($newstitle);
Vevb.com$content = $doc -> createTextNode($_content);//节点值
Vevb.com$author = $doc -> createAttribute('author');
$newsauthor = $doc -> createTextNode($_author);
$author -> appendChild($newsauthor);
Vevb.com$sendtime = $doc -> createAttribute('time');
$newssendtime = $doc -> createTextNode($_sendtime);
$sendtime -> appendChild($newssendtime);
Vevb.com$index -> appendChild($id);//将$id设为index节点的属性,以下类同
$index -> appendChild($title);
$index -> appendChild($content);
$index -> appendChild($url);
$index -> appendChild($author);
$index -> appendChild($sendtime);
Vevb.com$root -> appendChild($index);//设置index为root字节点
Vevb.com$doc -> appendChild($root);//设置root为跟节点
Vevb.com$doc -> save($xmlpatch);//保存文件
Vevb.comecho $xmlpatch . ' has create success';
Vevb.com?>
Vevb.com<!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>
Vevb.com<body>
</body>
</html>
//add.php 增加功能(跟index.php文件差不多,主要就是加个load载入跟 $root = $doc -> documentElement获得跟节点
代码如下:
<?php
$xmlpatch = 'index.xml';
$_id = '2';
$_title = 'title2';
$_content = 'content2';
$_author = 'author2';
$_sendtime = 'time2';
$_htmlpatch = '2.html';
Vevb.com$doc = new DOMDocument();
$doc -> formatOutput = true;
if($doc -> load($xmlpatch)) {
$root = $doc -> documentElement;//获得根节点(root)
$index = $doc -> createElement('index');
Vevb.com$url = $doc -> createAttribute('url');