在 PHP DOM 中获取节点的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6399924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:15:21  来源:igfitidea点击:

Getting node's text in PHP DOM

phphtmlxmldom

提问by bgcode

How could I extract the string "text" from this markup using the PHP DOM?

如何使用 PHP DOM 从此标记中提取字符串“text”?

<div><span>notthis</span>text</div>

$div->nodeValueincludes "notthis"

$div->nodeValue包括“notthis”

采纳答案by alex

So long as you can affect the DOM, you could remove that span.

只要你能影响 DOM,你就可以删除那个span.

$span = $div->getElementsByTagName('span')->item(0);
$div->removeChild($span);

$nodeValue = $div->nodeValue;

Alternatively, just access the text node of $div.

或者,只需访问$div.

foreach($div->childNodes as $node) {

    if ($node->nodeType != XML_TEXT_NODE) {
        continue;
    }
    $nodeValue = $node;
}

If you end up with more text nodes and only want the first, you can breakafter the first assignment of $nodeValue.

如果你最终得到更多的文本节点并且只想要第一个,你可以break在第一次分配$nodeValue.

回答by netcoder

You can access DOMTextnode directly using XPath:

您可以DOMText使用 XPath 直接访问节点:

$xpath = new DOMXPath($dom_document);
$node = $xpath->query('//div/text()')->item(0);
echo $node->textContent; // text