PHP操作XML [增删查改]

项目截图: 
需求:图中的数据用XML存储、读取、删除、修改



目标XML文件(net_config.xml):

<?xml version="1.0" encoding="UTF-8"?>
<nets>
  <line>
   <name id="1">10.0.101.0</name>
   <address>10.0.101.0</address>
   <mask>255.255.255.0</mask>
   <type>网络共享</type>
   <date>20140324</date>
 </line> 
<line><name>10.0.4.19</name><address>10.0.4.19</address><mask>0.0.0.0</mask><type>share</type><date>1395655669</date></line>
<line><name>10.0.4.15</name><address>10.0.4.15</address><mask>0.0.0.0</mask><type>share</type><date>1395655673</date></line>
<line><name>123</name><address>123</address><mask>0.0.0.0</mask><type>share</type><date>1395655678</date></line>
<line><name>222</name><address>22</address><mask>255.255.192.0</mask><type>share</type><date>1395655845</date></line>

</nets>
如何新增一个节点?


$xml_path="./public/xml/net_config.xml";//xml路径
$post_name=$this->input->post('name');//提交过来的name值
$post_address=$this->input->post('network');//提交过来的ip地址
$post_mask=$this->input->post('netmask');//提交过来的子网掩码
$post_type=$this->input->post('ntype');	//提交过来的类型
$post_date=time();	//时间戳
				
$doc = new DomDocument(); //创建一个新的 DOM对象
$doc->load($xml_path); //读取 XML数据
$lines = $doc->documentElement; //获得 XML结构的根
//创建一个新 line节点
$line = $doc->createElement('line');
$lines->appendChild($line);
//在新的 line节点上创建 name标签
$name = $doc->createElement('name');
$name->appendChild($doc->createTextNode($post_name));
$line->appendChild($name);
//在新的 line节点上创建 address标签
$address = $doc->createElement('address');
$address->appendChild($doc->createTextNode($post_address));
$line->appendChild($address);
//在新的 line节点上创建 mask标签
$mask = $doc->createElement('mask');
$mask->appendChild($doc->createTextNode($post_mask));
$line->appendChild($mask);
//在新的 line节点上创建 type标签
$type = $doc->createElement('type');
$type->appendChild($doc->createTextNode($post_type));
$line->appendChild($type);
//在新的 line节点上创建 date标签
$date = $doc->createElement('date');
$date->appendChild($doc->createTextNode($post_date));
$line->appendChild($date);
//将 XML数据写入文件
$fp = fopen($xml_path, "w");
if(fwrite($fp, $doc->saveXML())){				
echo 'success';
}else{
echo 'error'; }
fclose($fp); 

如何删除一个节点?

$doc = new DomDocument(); //创建一个新的 DOM对象
$doc->load($xml_path); //读取 XML数据
$root = $doc->documentElement; //获得 XML结构的根
$line = $doc->getElementsByTagName("line");				
foreach($line as $value){
$name = $value->getElementsByTagName( "name" )->item(0)->nodeValue;
if($name=='222'){//222为要删除的节点的name值
		$value->parentNode->removeChild($value);
		}
}
$doc->save($xml_path);
如何读取xml ?


$xml = simplexml_load_file($xml_path);
$networks=$xml->line ;//$networks为数组 循环读出即可

分享至
2014-03-24 发布 ┊ 3023 人浏览 ┊ 4 人评论 ┊ 来源:原创 ┊ 收藏
回复
  • # 2jzsz 2014-12-03 13:25┆
    学习了
  • # 4ye11lv 2015-12-01 15:48┆
    谢谢了
返回顶部