Option DOMDocument + XPath:
$xml = new DOMDocument(); $xml->loadHtml($temp); $xpath = new DOMXPath($xml); $html = ''; foreach ($xpath->query('//div[@id="main"]/*') as $node) { $html .= $xml->saveXML($node); }
If you are looking for innerHTML() (PHP DOMDocument help question) - instead of innerXML() , as in this answer - the xpath related option is provided in this answer .
Here the adoption with changes is emphasized:
$html = ''; foreach ($xpath->query('//div[@id="main"]/node()') as $node)
source share