【发布时间】:2011-09-18 00:00:20
【问题描述】:
如何使用 PHP DOM 从该标记中提取字符串“text”?
<div><span>notthis</span>text</div>
$div->nodeValue 包括“notthis”
【问题讨论】:
如何使用 PHP DOM 从该标记中提取字符串“text”?
<div><span>notthis</span>text</div>
$div->nodeValue 包括“notthis”
【问题讨论】:
您可以直接使用 XPath 访问DOMText 节点:
$xpath = new DOMXPath($dom_document);
$node = $xpath->query('//div/text()')->item(0);
echo $node->textContent; // text
【讨论】:
只要您可以影响 DOM,您就可以删除 span。
$span = $div->getElementsByTagName('span')->item(0);
$div->removeChild($span);
$nodeValue = $div->nodeValue;
或者,只需访问$div 的文本节点。
foreach($div->childNodes as $node) {
if ($node->nodeType != XML_TEXT_NODE) {
continue;
}
$nodeValue = $node;
}
如果你最终有更多的文本节点并且只想要第一个,你可以在$nodeValue的第一个分配之后break。
【讨论】: