发一个XML操作类(正则版)

来源:互联网 发布:淘宝算命 编辑:程序博客网 时间:2024/06/06 09:08
fpath=$fpath;$this->root=$root;$this->enter=chr(13).chr(10);$this->checkFile();}/**函数名:insert*说明:插入一条记录*/public function insert($fields){$content=$this->getFileContent();preg_match_all('|(/d+?)<//key>|',$content,$matches);rsort($matches[1]);$newkey=$matches[1][0]+1;$record=''.$this->enter;$record.=''.$newkey.''.$this->enter;foreach($fields as $k=>$v){$record.="<$k>$v".$this->enter;}$record.=''.$this->enter.$this->enter;$this->save(preg_replace('/(?=<//'.$this->root.'>)/',$record,$content));return true;}/**函数名:insertM*说明:插入多条记录,参数类型必须是二维数组*/public function insertM($arr){$content=$this->getFileContent();preg_match_all('|(/d+?)<//key>|',$content,$matches);rsort($matches[1]);$newkey=$matches[1][0]+1;$record='';for($i=0;$ienter;$record.=''.$newkey.''.$this->enter;foreach($arr[$i] as $k=>$v){$record.="<$k>$v".$this->enter;}$record.=''.$this->enter.$this->enter;$newkey++;}$this->save(preg_replace('/(?=<//'.$this->root.'>)/',$record,$content));return true;}/**函数名:checkFile*说明:如果文件不存在,则创建之,并初始化*     否则检查文件规则是否被破坏*/private function checkFile(){if(!file_exists($this->fpath)){$xmlstr='';$xmlstr=''.$this->enter;$xmlstr.='<'.$this->root.'>'.$this->enter.$this->enter;$xmlstr.='root.'>';$this->save($xmlstr);}else{$content=$this->getFileContent();$bool_statement=preg_match('/</?xml version="1/.0".*?/?>/',$content)==0 ? false : true;$bool_root=preg_match('/<'.$this->root.'>.*<//'.$this->root.'>/s',$content)==0 ? false : true;preg_match_all('|((?:.+?)<//record>)|s',$content,$matches);for($i=0;$igetFileContent();preg_match('/(/s*'.$id.'<//key>.+?)<//record>/s',$content,$matches);preg_match_all('|(<.+)|',$matches[1],$arr);$arrstr='';for($i=0;$i(.+)<//(.+)>/',$arr[1][$i],$farr);$arrstr.="'$farr[2]'=>'$farr[1]'";if($igetFileContent();foreach($form_arr as $k=>$v){$re='/('.$id.'<//key>[/s/S]*?<'.$k.'>).+?(<//'.$k.'>)/s';$content=preg_replace($re,'${1}'.$v.'$2',$content);}$this->save($content);return true;}public function deleteRecordById($id){$content=$this->getFileContent();$content=preg_replace('//s*'.$id.'+.+?<//record>(/s{4})?/s','',$content);$this->save($content);}/**函数名:getList*说明:获取所有记录,返回一个二维数组*     先获取所有record记录,再获取字段名和值*/public function getList(){$content=$this->getFileContent();$rs=array();preg_match_all('|(.+?)<//record>|s',$content,$matches);for($i=0;$i)|',$matches[1][$i],$tmparr);$arrstr='';for($j=0;$j(.+)<//(.+)>/',$tmparr[1][$j],$farr);$arrstr.="'$farr[2]'=>'$farr[1]'";if($jfpath,'r');$content=fread($hd,filesize($this->fpath));fclose($hd);return $content;}private function save($content){$hd=fopen($this->fpath,'w');fwrite($hd,$content);fclose($hd);}}?>

 

使用例子

 

 

'pangmen','sex'=>'男','tel'=>'139999999','address'=>'北京');$x->insert($arr);//删//$x->deleteRecordById(1);//改//$arr=array('username'=>'pangmen','sex'=>'男','tel'=>'139999999','address'=>'北京');//$x->updateRecordById(1,$arr);//查(一条记录)//print_r($x->getRecordById(1));//查(所有记录)//print_r($x->getList());?>