Delete all elements of a certain type from an XML doc using PHP

ぃ、小莉子 提交于 2019-11-28 14:19:49

Goal is to delete whole node leaving other nodes ( in actual there are more, but for simplicity this example shows all

$dom = new DOMDocument;
$dom->load('places.xml');
foreach ($dom->getElementsByTagName('places') as $places)
{
    $places->parentNode->removeChild($places);
}
echo $dom->saveXml();

will remove all <places> elements anywhere in the document, including any children.

Output:

<?xml version="1.0"?>
<piletilve_info>

   <other>
      ...
   </other>
</piletilve_info>

When I was using the accepted answer it wouldn't remove all occurrences of the tag. The foreach loop would skip over tags probably because foreach relies on the internal array pointer and changing it within the loop leads to unexpected behavior.

A working solution that I've found looks like this.

$dom = new DOMDocument;
$dom->load('places.xml');
$placesNodes = $dom->getElementsByTagName('places') 
while ($placesNodes->length > 0) {
    $node = $placesNodes->item(0);
    $node->parentNode->removeChild($node);
}
echo $dom->saveXml();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!