<?php
class Conf {
private $file;
private $xml;
private $lastmatch;
function __construct( $file ) {
$this->file = $file;
//使用异常方式检查文件存在不
if ( ! file_exists( $file ) ) {
throw new Exception( "文件 '$file' 不存在 " );
}
$this->xml = simplexml_load_file($file);
}
function write() {
if ( ! is_writable( $this->file ) ) {
throw new Exception( "文件 '{$this->file}' 不可写 " );
}
file_put_contents( $this->file,$this->xml->asXML() );
}
function get( $str ) {
$matches = $this->xml->xpath( "/conf/item[@name=\"$str\"]" );
if ( count( $matches ) ) {
$this->lastmatch = $matches[0];
return (string)$matches[0];
}
return null;
}
//设置XML item标签 属性与值
function set( $key,$value ) {
if ( ! is_null( $this->get( $key ) ) ) {
$this->lastmatch[0] = $value;
return;
}
$conf = $this->xml->conf;
$this->xml->addChild( 'item', $value )->addAttribute( 'name', $key );
}
}
try{
$xml = new Conf("files.xml");//导入XML文件
$xml->set("test", "aaaa");//设置item标签属性与值
$xml->write();//写入xml文件
} catch ( Exception $e ) {
die ( $e->__toString() );//输出出错信息
}
转载于:https://my.oschina.net/qq277049/blog/41172