PHP 8.5.0 Alpha 4 available for testing

Voting

: four plus three?
(Example: nine)

The Note You're Voting On

felix dot klee at inka dot de
12 years ago
How to rename an element and preserve attributes:

<?php

// Changes the name of element $element to $newName.
function renameElement($element, $newName) {
$newElement = $element->ownerDocument->createElement($newName);
$parentElement = $element->parentNode;
$parentElement->insertBefore($newElement, $element);

$childNodes = $element->childNodes;
while (
$childNodes->length > 0) {
$newElement->appendChild($childNodes->item(0));
}

$attributes = $element->attributes;
while (
$attributes->length > 0) {
$attribute = $attributes->item(0);
if (!
is_null($attribute->namespaceURI)) {
$newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
'xmlns:'.$attribute->prefix,
$attribute->namespaceURI);
}
$newElement->setAttributeNode($attribute);
}

$parentElement->removeChild($element);
}

function
prettyPrint($d) {
$d->formatOutput = true;
echo
'<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument( '1.0' );
$d->loadXML('<?xml version="1.0"?>
<library>
<data a:foo="1" x="bar" xmlns:a="http://example.com/a">
<invite>
<username>jmansa</username>
<userid>1</userid>
</invite>
<update>1</update>
</data>
</library>'
);

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if (
$elements->length == 1) {
$element = $elements->item(0);
renameElement($element, 'invites');
}

prettyPrint($d);

?>

<< Back to user notes page

To Top