Home » Php » PHP + Simple HTML DOM: Select a tag inside a div with class inside another div with class

PHP + Simple HTML DOM: Select a tag inside a div with class inside another div with class

Posted by: admin February 25, 2020 Leave a comment

Questions:

In PHP: Simple HTML DOM, How do I select all <strong> tag that are inside div with class abc, which are inside div with class 123:

<div class="123">
 <div class="abc">
  <strong>Text</strong>
 </div>
</div>
How to&Answers:

You need to use a selector like div.123 div.abc strong and get the first element of the result. Here is a working example:

<?php

require 'simple_html_dom.php';

$html =<<<html
<div class="123">
 <div class="abc">
  <strong>Text</strong>
 </div>
</div>
html;                                                                                                                                                                                                                                         

$dom = str_get_html($html);
$el = $dom->find('div.123 div.abc strong', 0);
print $el;
print "\n";
print $el->innertext;

Result:

<strong>Text</strong>
Text

You can refer to the manual for a better understanding of how selectors work.