简体   繁体   English

重命名PHP中的XML DOM节点

[英]Rename XML DOM node in PHP

How do I rename an XML node in DOMDocument? 如何在DOMDocument中重命名XML节点? I want to make a backup of a node in an XML file before writing a new node. 我想在写入新节点之前对XML文件中的节点进行备份。 I have this code where I want to rename the URLS node to URLS_BACKUP. 我在此代码中将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');
}

The XML file has this structure. 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>

Thanks. 谢谢。

you read the whole list of xml file with fopen and you used the method str_replace () 您使用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');

It is not possible to rename a node in a DOM. 重命名DOM中的节点是不可能的。 String functions might work but the best solution is to create a new node and replace the old. 字符串函数可能有效,但是最好的解决方案是创建一个新节点并替换旧节点。

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);

$nodeId = 'c000002'; 
$nodes = $xpath->evaluate("//COMMUNITY[@ID='$nodeid']/URLS");

// we change the document, iterate the nodes backwards
for ($i = $nodes->length - 1; $i >= 0; $i--) {
  $node = $nodes->item($i);
  // create the new node
  $newNode = $dom->createElement('URL_BACKUP');
  // copy all children to the new node
  foreach ($node->childNodes as $childNode) {
    $newNode->appendChild($childNode->cloneNode(TRUE));
  }
  // replace the node
  $node->parentNode->replaceChild($newNode, $node);
}

echo $dom->saveXml();

Knowing it's not possible, here is a simpler function for renaming the tag once the file is saved: 知道这是不可能的,这是一个更简单的函数,用于在文件保存后重命名标签:

/**
 * renames a word in a file
 *
 * @param string $xml_path
 * @param string $orig word to rename
 * @param string $new new word
 * @return void
 */
public function renameNode($xml_path,$orig,$new)
{
    $str=file_get_contents($xml_path);
    $str=str_replace($orig, $new ,$str);
    file_put_contents($xml_path, $str);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM