<?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,null,LIBXML_NOERROR);
if(!is_object($this->xml)){
throw new XmlException(libxml_get_last_error());
}
print gettype($this->xml)."<br>";
}
function write(){
if(!is_writeable($this->file)){
throw new Exception('文件{$this->file}不能写入');
}
file_put_contents($this->file,$this->xml->asXML());
}
function get($str){
$matches=$this->xml->xpath("item[@name=\"$str\"]");
if(count($matches)){
$this->lastmatch=$matches[0];
return (string)$matches[0];
}
return null;
}
function set($key,$value){
if(!is_null($this->get($key))){
$this->lastmatch[0]=$value;
return;
}
$conf=$this->xml->conf;
$re=$this->xml->addChild('item',$value);
$re->addAttribute('name',$key);
}
}
class XmlException extends Exception{
private $error;
function __construct(LibXmlError $error){
$shortfile=basename($error->file);
$msg="[{$shortfile},line{$error->line},col{$error->col}]{$error->message}";
$this->error=$error;
parent::__construct($msg,$error->code);
}
function getLibXmlError(){
return $this->error;
}
}
class Runner{
static function init(){
try{
$conf=new Conf(dirname(__FILE__)."/simplexml.xml");
echo "user:".$conf->get('user')."<br>";
echo "host:".$conf->get('host')."<br>";
$conf->set("pass","newpass");
$conf->write();
}catch(XmlException $e){
throw new XmlException(libxml_get_last_error());
}catch(FileException $e){
throw new FileException(libxml_get_last_error());
}
}
}
Runner::init();
?>
10-29
456
03-02
162
07-30
7121