user823527
user823527

Reputation: 3712

Rename XML DOM node in PHP

How do I rename an XML node in DOMDocument? I want to make a backup of a node in an XML file before writing a new node. I have this code where I want to rename the URLS node to 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 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.

Upvotes: 0

Views: 1938

Answers (3)

javier_domenech
javier_domenech

Reputation: 6263

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);
}

Upvotes: -1

ThW
ThW

Reputation: 19502

It is not possible to rename a node in a 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();

Upvotes: 2

Thierry Snaet
Thierry Snaet

Reputation: 154

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

Upvotes: 5

Related Questions