innerHTML in xPath?

后端 未结 4 510
醉话见心
醉话见心 2021-01-14 17:33

Is there a way of retrieving HTML (and JavaScript) contained in a div element?

相关标签:
4条回答
  • 2021-01-14 17:54

    This will give you the outerHTML rather than the innerHTML, but you can easily strip the extra DIV tags at both ends.

    Working example:

    $xpath = new DOMXPath( @DOMDocument::loadHTML($the_html_code) ) ;
    $domElement = $xpath->evaluate("//div[@id='ID_of_the_div']")->item(0) ;
    $outerHTML = $domElement->ownerDocument->saveXML($domElement) ;
    
    0 讨论(0)
  • 2021-01-14 17:58

    Now about:

    //div[@id='your div']

    If you don't care about performance?

    0 讨论(0)
  • 2021-01-14 18:16

    I'm not a PHP developer but I found this:

    function getNodeInnerHTML(DOMNode $oNode)
    {
        $oDom = new DOMDocument();
        foreach($oNode->childNode as $oChild)
        {
            $oDom->appendChild($oDom->importNode($oChild, true));
        }
        return $oDom->saveHTML();
    }
    

    from http://www.sitepoint.com/forums/showthread.php?p=4225203

    I don't think you can select content including with only XPath, so a function like the one above may be necessary. And then you select your div like //div[@id='someID'] etc.

    0 讨论(0)
  • 2021-01-14 18:17
    $xml=new DOMDOCUMENT();
    @$xml->loadHTML($htmlcontents);
    $xpath=new DOMXPATH($xml);
    $nodes=$xpath->query($xpath);
    
    function getHtml($nodes) {
        $result = '';
        foreach ($nodes as $node) {
            $result .= $node->ownerDocument->saveHtml($node);
        }
    return $result;
    }
    

    Source: how to get innerhtml by classname or id using php

    0 讨论(0)
提交回复
热议问题