Fawaz Fawaz - 5 months ago 8
PHP Question

Get content of special HTML tag by class name

If I have an HTML page containing

<div class="post-inner">
, how can I get the content of this
div
with class name
post-inner
without any JavaScript? I just want the content of the
div
tag using PHP as fast as possible. I have tried this code but I don't know what to do after that:

$html = file_get_contents('http://www.q8ping.com/49352.html');
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$sxml = simplexml_import_dom($doc);
print_r($sxml);

Answer

You can use XPath to accomplish that. Change your code to this:

$html = file_get_contents('http://www.q8ping.com/49352.html');
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$finder = new DomXPath($doc);
$node = $finder->query("//*[contains(@class, 'post-inner')]");
print_r($doc->saveHTML($node->item(0)));

You might want to check first though if an element was found.