Home » Php » Find first div with class use simple HTML DOM

Find first div with class use simple HTML DOM

Posted by: admin October 26, 2017 Leave a comment


I’m using simple html dom to get data from a website.

My problem is when i find a div with a specify class it return all the div tag which have that class.
I’m want content in the first div with that class only.

My code is like this

$html = file_get_html('myurl');
$e = $html->find("div[class=myclass]",0);
echo $e->plaintext; 

How can i get the first div with myclass only.
Sorry for my bad English


The find method is returning an array of HTML elements. That means to get the first you’ll need to select the first index from the returned array. Simply change to


This will select the first element in the array.


Try this alternative method,

$e = $html->find("div[class=myclass]");
echo $e[0]->plaintext;

However it should also work with $html->find("div[class=myclass]",0);
I only had to change $html = file_get_html(myurl); to $html = str_get_html(file_get_contents(myurl)); for my version of simple_html_dom with php 7