images.xml文件的格式:
<?xml version="1.0" encoding="utf-8"?>
<root imageWidth="680" imageHeight="345">
</root>
读取:
<?php
$doc = new DOMDocument();
$doc->load( 'images.xml' );
$root = $doc -> documentElement;
echo $root-> getAttribute("imageWidth")."<br>";
echo $root-> getAttribute("imageHeight")."<br>";
$menus = $root->getElementsByTagName_r( "menu" );
//只能读取前三条,后三条读不到
foreach( $menus as $menu )
{
}
//只能读取后三条,前三条读不到
foreach( $menus as $menu )
{
}
?>
XML文件的创建、添加、修改:
<?php
$xmlpatch = 'index.xml';
$_id = '1';
$_title = 'title1';
$_content = 'content1';
$_author = 'author1';
$_sendtime = 'time1';
$_htmlpatch = '11111.html';
$doc = new DOMDocument('1.0', 'utf-8');
$doc -> formatOutput = true;
$root = $doc -> createElement_x_x_x('root');//新建节点
$index = $doc -> createElement_x_x_x('index');//新建节点
$url = $doc -> createAttribute('url');//新建属性
$patch = $doc -> createTextNode($_htmlpatch);//新建TEXT值
$url -> a($patch);//将$patch文本设为$url属性的值
$id = $doc -> createAttribute('id');
$newsid = $doc -> createTextNode($_id);
$id -> a($newsid);
$title = $doc -> createAttribute('title');
$newstitle = $doc -> createTextNode($_title);
$title -> a($newstitle);
//$content = $doc -> createTextNode($_content);//节点值
$author = $doc -> createAttribute('author');
$newsauthor = $doc -> createTextNode($_author);
$author -> a($newsauthor);
$sendtime = $doc -> createAttribute('time');
$newssendtime = $doc -> createTextNode($_sendtime);
$sendtime -> a($newssendtime);
$index -> a($id);//将$id设为index节点的属性,以下类同
$index -> a($title);
//$index -> a($content);
$index -> a($url);
$index -> a($author);
$index -> a($sendtime);
$root -> a($index);//设置index为root字节点
$doc -> a($root);//设置root为跟节点
$doc -> save($xmlpatch);//保存文件
echo $xmlpatch . ' has create success';
?>
创建出的XML文件如下:
<?xml version="1.0" encoding="utf-8"?>
<root>
</root>
添加:
<?php
//add.php 增加功能(跟index.php文件差不多,主要就是加个load载入跟 $root = $doc -> documentElement获得跟节点
$xmlpatch = 'index.xml';
$_id = '2';
$_title = 'title2';
$_content = 'content2';
$_author = 'author2';
$_sendtime = 'time2';
$_htmlpatch = '2.html';
$doc = new DOMDocument();
$doc -> formatOutput = true;
if($doc -> load($xmlpatch)) {
} else {
}
?>
修改:
<?php
//edit.php 修改功能(这里只修改title属性值 跟节点值)
$xmlpatch = 'index.xml';
$_id = '2';
$_title = 'has been changed';
$_content = 'has been changed';
$doc = new DOMDocument();
$doc -> formatOutput = true;
if($doc -> load($xmlpatch)) {
} else {
}
?>
删除:
<?php
//del.php 删除功能
$xmlpatch = 'index.xml';
$_id = '2';
$doc = new DOMDocument();
$doc -> formatOutput = true;
if($doc -> load($xmlpatch)) {
} else {
}
?>