Parse HTML with PHP's HTML DOMDocument

The text inside a

tag inside class="text" inside
with class="main" can be obtained with the following code −

Example

$html = <<<HTML
<div class="main">
  <div class="text">
    This is text 1
  </div>
</div>
<div class="main">
  <div class="text">
    This is text 2
  </div>
</div>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[@class="main"]/div[@class="text"]');
foreach ($tags as $tag) {
  var_dump(trim($tag->nodeValue));
}

Output

This will produce the following output −

string 'This is text 1' (length=14)
string 'This is text 2' (length=14)
Updated on: 2020-04-07T11:36:35+05:30

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements