首页 > 开发 > PHP > 正文

php xml节点 修改,增加,编辑,删除代码

2024-05-04 21:58:40
字体:大 中 小
来源:转载
供稿:网友

本教程是利用了php domdocument函数来对xml节点 修改,增加,编辑,删除代码下面每个操作节点都是英文说明,如果你能写程序我想这些英文都能看得懂的.

php xml节点 修改,增加,编辑,删除代码如下:

  1. function loadfile($file){ 
  2.   $newfile=new domdocument(); 
  3.   $newfile->validateonparse=true; 
  4.   $newfile->load($file); 
  5.    
  6.   return $newfile; 
  7. } 
  8. function add($file, $parentname, $children){ //增加xml节点 
  9.   $xml=loadfile($file); 
  10.    
  11.   $id=uniqid('m' . rand(1,5), true); 
  12.   $parentnode=$xml->createelement($parentname); 
  13.   $parentnode->setattribute('mid', $id); 
  14.   foreach($children as $child => $value){ 
  15.     $childnode=$xml->createelement($child, $value); 
  16.     $parentnode->appendchild($childnode); 
  17.   } 
  18.   $xml->documentelement->appendchild($parentnode); 
  19.   $xml->save($file); 
  20.   return $id; 
  21. } 
  22. function delete($file, $id){//删除xml 节点 
  23.   $xml=loadfile($file); 
  24.   $ids=explode(",", $id); 
  25.   foreach ($ids as $oldnodeid){ 
  26.     $oldnode=$xml->getelementbyid($oldnodeid); 
  27.     $parentnode=$oldnode->parentnode; 
  28.     $parentnode->removechild($oldnode); 
  29.   } 
  30.   $xml->save($file); 
  31. } 
  32. function edit($file, $id, $child, $value){//编辑xml 节点 
  33.   $xml=loadfile($file); 
  34.    
  35.   $parentnode=$xml->getelementbyid($id); 
  36.   $childnode=$parentnode->childnodes->item($child); 
  37.   $textnode=$childnode->childnodes->item(0); 
  38.   $textnode->nodevalue=$value; 
  39.    
  40.   $xml->save($file); 
  41. } 
  42. function move($file, $moveid, $refid=null){ //移动xml节点 
  43.   $xml=loadfile($file); 
  44.    
  45.   $movenode=$xml->getelementbyid($moveid); 
  46.   $parentnode=$movenode->parentnode; 
  47.   if ($refid!=null) { 
  48.     $refnode=$xml->getelementbyid($refid); 
  49.     if(!$parentnode->issamenode($refnode->parentnode)) return false; 
  50.   } 
  51.   else $refnode=null; 
  52.   $movenode=$parentnode->removechild($movenode); 
  53.   $parentnode->insertbefore($movenode,$refnode); 
  54.   //开源代码Vevb.com 
  55.   $xml->save($file); 
  56. } 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表