1 回答
TA贡献2036条经验 获得超8个赞
getElementsByTagName()将返回“实时”结果。如果您修改文档,它将发生变化。您可以用来iterator_to_array()制作稳定的副本。
另一种选择是使用 Xpath 表达式来获取特定节点。
$document = new DOMDocument();
$document->loadXML($xmlString);
$xpath = new DOMXpath($document);
// fetch items that contain "filter" in their description
$items = $xpath->evaluate('/rss/channel/item[contains(description, "filter")]');
foreach ($items as $item) {
// dump the title child element text content
var_dump($xpath->evaluate('string(title)', $item));
}
// fetch items that do not contain "filter" in their description
$items = $xpath->evaluate('/rss/channel/item[not(contains(description, "filter"))]');
foreach ($items as $item) {
// remove item element
$item->parentNode->removeChild($item);
}
echo $document->saveXML();
输出:
string(8) "Title #1"
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>Title</title>
<link/>
<item>
<title>Title #1</title>
<description>Here I want to filter</description>
</item>
</channel>
</rss>
- 1 回答
- 0 关注
- 172 浏览
添加回答
举报