Getting node's text in PHP DOM

前端 未结 2 539
无人共我
无人共我 2020-11-28 13:32

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

notthistext

相关标签:
2条回答
  • 2020-11-28 13:51

    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 讨论(0)
  • 2020-11-28 13:51

    You can access DOMText node directly using XPath:

    $xpath = new DOMXPath($dom_document);
    $node = $xpath->query('//div/text()')->item(0);
    echo $node->textContent; // text
    
    0 讨论(0)
提交回复
热议问题