Answer the question
In order to leave comments, you need to log in
PHP+XPath, how to parse an html fragment without having to traverse all nested nodes in the resulting object to save the result?
I'm trying to get an html fragment containing a lot of child nodes. Example:
<body>
<table>...</table>
<div>
<p>Sometext 1<br> Sometext2</p>
<p>Sometext 3</p>
</div>
</body>
$xquery = '//div/node()';
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$results = $xpath->query($xquery);
foreach($results as $key){
$parsed_html .= $key->nodeValue;
}
Answer the question
In order to leave comments, you need to log in
easier than regular IMHO. And faster. And eat less memory.
Well, or implode("",$results);
Here is an example of a working code, but I advise you to make it a separate method or function, at least to pass DOMNode into it:
$results = $xpath->query('//div[@class="example"]'); // тут путь до элемента, внутренности которого нужны
$innerHTML = '';
$children = $results->item(0)->childNodes;
foreach ($children as $child)
$innerHTML .= $results->item(0)->ownerDocument->saveHTML($child);
echo $innerHTML; // тут все внутренности
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question