I have an XML file that currently has 4 nodes with the same name: The file looks like this: (data.xml)
<?xml version="1.0"?>
<products>
<product>
<ItemId>531670</ItemId>
<modelNumber>METRA ELECTRONICS/MOBILE AUDIO</modelNumber>
<name>Buy</name>
<name>Car, Marine & GPS</name>
<name>Car Installation Parts</name>
<name>Deck Installation Parts</name>
<name>Antennas & Adapters</name>
</product>
</products>
There are 4 nodes with the same name. (the name node).
I then use this PHP code to replace the node names
<?php
/**
* @param $xml string Your XML
* @param $old string Name of the old tag
* @param $new string Name of the new tag
* @return string New XML
*/
function renameTags($xml, $old, $new)
{
$dom = new DOMDocument();
$dom->loadXML($xml);
$nodes = $dom->getElementsByTagName($old);
$toRemove = array();
foreach ($nodes as $node)
{
$newNode = $dom->createElement($new);
foreach ($node->attributes as $attribute)
{
$newNode->setAttribute($attribute->name, $attribute->value);
}
foreach ($node->childNodes as $child)
{
$newNode->appendChild($node->removeChild($child));
}
$node->parentNode->appendChild($newNode);
$toRemove[] = $node;
}
foreach ($toRemove as $node)
{
$node->parentNode->removeChild($node);
}
return $dom->saveXML();
}
// Load XML from file data.xml
$xml = file_get_contents('data.xml');
$xml = renameTags($xml, 'name', 'newName');
echo $xml;
?>
This function replaces all of the name nodes with newName; however, I want to only replace one instance of the name tag because I want to rename each of the name tags. If I call another $xml = renameTags($xml, 'name', 'newName2');
It wont work, it will only use the first instance of $xml.
Any Idea how I can change my code to allow me to replace each name node individually?