im trying to make a function that returns the inner HTML of a div with a spesific classname.
i searched around and people seem to say xpath query is the way to go.
this is what i got:
function getDivContent($html, $classname) {
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query('//div[class="'.$classname.'"]');
return $result;
}
but it only returns:
object(DOMNodeList)#3 (0) { }
anyone can spot the error?
EDIT: The solution:
function nodeContent($n, $outer=false) {
$d = new DOMDocument('1.0');
$b = $d->importNode($n->cloneNode(true),true);
$d->appendChild($b); $h = $d->saveHTML();
// remove outter tags
if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4));
return $h;
}
function getDivContentByClass($html, $class) {
$query = "//div[@class='$class']";
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query($query);
$data = nodeContent($result->item(0));
return $data;
}
xpath’s query function returns a NODEList, which is essentially an array of the results, even if there’s only a single matching node.
will return the first matching node only. To get the content, you can use
$result->item(0)->nodeValue, which acts equivalently to .innerHTML.