2012-10-09 120 views
0

我想在php中使用dom removeChild函数来删除标签之间的所有内容。如何通过标签名称与其中的所有元素删除元素

我的XML看起来像

<root> 
    <element>text</element> 

    <remove> 
    text 
    <morexml>text</morexml> 
    </remove> 
</root> 

现在我想删除里面包括整个的标签。我该怎么做呢?我没有线索。我正在尝试使用我发现的唯一dom函数:removeChild。

当去除它看起来像这样:

<root> 
     <element>text</element> 

</root> 

是否有一个PHP DOM功能做到这一点?我无法在Google或者stackoverflow上找到它。

+0

http://stackoverflow.com/questions/1153697/php-delete-xml-element – jcho360

+0

你可以尝试用正则表达式来做到这一点:如果你需要更多的普遍性,您可以使用XPath。以下链接可能会帮助你:http://stackoverflow.com/questions/226562/how-can-i-remove-an-entire-html-tag-and-its-contents-by-its-class-using-a-雷杰 – kjurkovic

回答

1
$dom = new DOMDocument; 
$dom->loadXML($xml); 
$dom->getElementsByTagName('root')->item(0) 
    ->removeChild($dom->getElementsByTagName('remove')->item(0)); 

虽然这是非常具体的。

foreach ($xpath->query('//remove') as $node) { 
    $node->parentNode->removeChild($node); 
} 
相关问题