在PHP DOM中获取节点的文本 [英] Getting node's text in PHP DOM

查看:101
本文介绍了在PHP DOM中获取节点的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从PHP标记中提取字符串text?

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

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

$ div-> nodeValue

推荐答案

只要你可以影响DOM,你可以删除 span

So long as you can affect the DOM, you could remove that 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;
}

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

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

这篇关于在PHP DOM中获取节点的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆