在PHP中重命名XML DOM节点

use*_*527 0 php xml dom

如何在DOMDocument中重命名XML节点?我想在编写新节点之前备份XML文件中的节点.我有这个代码,我想将URLS节点重命名为URLS_BACKUP.

function backup_urls( $nodeid ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true; 
$dom->preserveWhiteSpace = true;

// get document element  

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']"); 

if ($nodes->length) {

   $node = $nodes->item(0); 

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   /* rename URLS to URLS_BACKUP */

   }

}

$dom->save('communities.xml');
}
Run Code Online (Sandbox Code Playgroud)

XML文件具有此结构.

<?xml version="1.0" encoding="ISO-8859-1"?>
<COMMUNITIES>
 <COMMUNITY ID="c000002">
  <NAME>ID000002</NAME>
  <TOP>192</TOP>
  <LEFT>297</LEFT>
  <WIDTH>150</WIDTH>
  <HEIGHT>150</HEIGHT>
  <URLS>
     <URL ID="u000002">
         <NAME>Facebook.com</NAME>
         <URLC>http://www.facebook.com</URLC>
     </URL>
  </URLS>
 </COMMUNITY>
</COMMUNITIES>
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 6

你用fopen读取了整个xml文件列表并使用了str_replace()方法

$ handle = fopen ('communities.xml', 'r');
while (! feof ($ handle))
{
       $ buffer = fgets ($ handle, 4012);
       $ buffer = str_replace ("URLS", "URLS_BACKUP", $ buffer);
}
fclose ($ handle);
$ dom-> save ('communities.xml');
Run Code Online (Sandbox Code Playgroud)