简单的xml处理类.

来源:互联网 发布:c 多线程编程面试题 编辑:程序博客网 时间:2024/06/05 22:42

<?php
header('content-type: text/html; charset=utf-8');
class OpXML
{
   
private $fpath;
   
private $enter;
   
private $root;

   
function __construct($root,$fpath)
    {
       
$this->fpath=$fpath;
       
$this->root=$root;
       
$this->enter=chr(13).chr(10);
       
$this->checkFile();
    }

   
/*
    *函数名:insert
    *说明:插入一条记录
   
*/
   
public function insert($fields)
    {
       
$content=$this->getFileContent();
               
       
$record='<partners>'.$this->enter;
       
foreach($fields as $k=>$v)
        {
           
$record.="<$k name=$v></$k>".$this->enter;
        }
       
$record.='</partners>'.$this->enter.$this->enter;
       
$this->save(preg_replace('/(?=<//'.$this->root.'>)/',$record,$content));
       
return true;
    }
   
private function checkFile()
    {
       
if(!file_exists($this->fpath))
        {
           
$xmlstr='';
           
$xmlstr='<?xml version="1.0" encoding="UTF-8"?>'.$this->enter;
           
$xmlstr.='<'.$this->root.'>'.$this->enter.$this->enter;
           
$xmlstr.='</'.$this->root.'>';
           
$this->save($xmlstr);
        }
   
    }
   
private function getFileContent()
    {
       
$hd=fopen($this->fpath,'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);
    }
}

$rootname='person';//根标签名
$fpath='./12.xml';//文件的路径,不用手动创建文件
$x=new OpXML('person',$fpath);
$name = $_post['children'];
if(!isset($name))$name="yuan";
//从form增加一条记录
$arr=array('partner'=>$name);
$x->insert($arr);

?>

原创粉丝点击