InnerHTML in xPath?

Is there a way to get the HTML (and JavaScript) contained in a div element?

+3
source share
4 answers

I am not a PHP developer, but 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 only XPath, so a function similar to the one above may be required. And then you select your div like //div[@id='someID']etc.

+2
source
$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 name or name using php

0
source

:

//div [@id = ' div']

?

-1
source

This will give you outerHTML, not innerHTML, but you can easily remove the extra DIV tags from 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) ;
-1
source

Source: https://habr.com/ru/post/1762584/


All Articles