开发者

Getting node's text in PHP DOM

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

<div><span>notthis</span>te开发者_StackOverflow社区xt</div>

$div->nodeValue includes "notthis"


You can access DOMText node directly using XPath:

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


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;

Alternatively, just access the text node of $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 break after the first assignment of $nodeValue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜