I have an XML file that looks something like this:
<product>
<modelNumber>Data</modelNumber>
<salePrice>Data</salePrice>
</product>
<product>
<modelNumber>Data</modelNumber>
<salePrice>Data</salePrice>
</product>
Is there a simple way to change the tag names , to something else such as model, price.
Essentially, I have a bunch of XML files containing similar data, but in different formats, so I'm looking for a simple way to parse the XML file, change certain tag names, and write a new XML file with the changed tag names.
If you run the XML file as a PHP script, then yes. The output of the script will be valid XML, but the file that contains the inline PHP will most likely not be valid XML. Save this answer.
Custom tags use XML syntax and are what page authors use. This is an umbrella term that describes the set of classes and conventions that allow programmers to create custom actions and tags within JSP. The tag extension mechanism was added to JSP in version 1.1.
The XML document must have start-tag, so first starting tag is known as root tag. The opening tag started with < bracket followed by tag name or element name and close with > bracket.
There are two issues with Kris and dfsq code:
A corrected renaming function is:
function renameTag( DOMElement $oldTag, $newTagName ) {
$document = $oldTag->ownerDocument;
$newTag = $document->createElement($newTagName);
$oldTag->parentNode->replaceChild($newTag, $oldTag);
foreach ($oldTag->attributes as $attribute) {
$newTag->setAttribute($attribute->name, $attribute->value);
}
foreach (iterator_to_array($oldTag->childNodes) as $child) {
$newTag->appendChild($oldTag->removeChild($child));
}
return $newTag;
}
Next function will do the trick:
/**
* @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, 'modelNumber', 'number');
$xml = renameTags($xml, 'salePrice', 'price');
echo '<pre>'; print_r(htmlspecialchars($xml)); echo '</pre>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With