Aller au contenu | Aller au menu | Aller à la recherche


PHP replace nodeName in DOMNode ?

How to change the name of a node element ?

The DOMNode class

public readonly string $DOMNode->nodeName ;

For replace a node name in XML Document with PHP, i use : How can I change the name of an element in DOM?

Thanks for this solution.

With PHP 5.3, `appendChild()` take only one argument, and for working, i `replaceChild()` on my parent element in my main code.

I have initialy try to use `cloneChild()` before seeing you reply, but this method keep name. The problem stay alive, "Cannot write property" because she was readonly.

The DOMNode class :

   public readonly string $DOMNode->nodeName ;
function changeNodeName($node, $name) {
	// http://stackoverflow.com/questions/775904/how-can-i-change-the-name-of-an-element-in-dom
	$newnode = $node->ownerDocument->createElement($name);
	foreach ($node->childNodes as $child){
		$child = $node->ownerDocument->importNode($child, true);
// 		$newnode->appendChild($child, true); // DOMNode::appendChild() expects exactly 1 parameter, 2 given
		$newnode->appendChild($child);
	}
	foreach ($node->attributes as $attrName => $attrNode) {
		$newnode->setAttribute($attrName, $attrNode);
	}
// 	var_dump($node->nodeName);
// 	var_dump($newnode->nodeName);
// 	$newnode->ownerDocument->replaceChild($newnode, $node);
	return $newnode;
}
 
$element = $doc->getElementsByTagName("myTagToReplace")->item(0);
$oldNode = $element->firstChild;
$newNode = changeNodeName($oldNode , 'myTagReplaced');
$element->replaceChild($newNode , $oldNode);

Ajouter un commentaire

Le code HTML est affiché comme du texte et les adresses web sont automatiquement transformées.

Fil des commentaires de ce billet