Tab123
Tab123

Reputation: 31

how to get html table element by classname in php

Here is a table whose classname is nick. I am trying to get this table by class name "nick".

<table  class="nick">
              <tbody>
              <tr>

                <th> a  </th>
                <th>    b</th>
                <th> c  </th>
          </tr>
 <tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
 </tr>

        </tbody></table>    

here is the code.

    include_once('simple_html_dom.php');
    $html = file_get_html('http://www.example.com');

  $table = $html->find('.nick');
  echo $table . '<br>';

?>

when i get table by tagname it works but when i get it by class name it shows the msg "Array to string conversion" and it returns "Array".

how can i get this table by class nick and its rows and coloms.Also threre are 2 table which has classname "nick".

Upvotes: 1

Views: 2645

Answers (3)

Kevin
Kevin

Reputation: 41875

You forgot to put the index inside ->find(). Without providing the index, this will return an array. When you put the index (in this case 0), you'll point to the first found element with that class.

$table = $html->find('.nick', 0);
                           // ^ this is important
echo $table;

Reference:

mixed find ( string $selector [, int $index] )

Find elements by the CSS selector. Returns the Nth element object if index is set, otherwise return an array of object.

Of course, the first table falls under zero index (0), the second on one (1).

If you want to go the extra mile, you can check first if there tables with that class name if you want the ->find() method untouched:

$table = $html->find('.nick');
if(count($table) > 0) { // if found
    echo $table[0]; // echo first table
} else {
    // not found
}

Upvotes: 4

Jalpa
Jalpa

Reputation: 720

You can get right html using class in php like below code.

include_once('simple_html_dom.php');
$html = file_get_html('http://www.example.com');

$table = $html->find('table.nick');
//OR
$table = $html->find('table[class=nick]');
echo $table . '<br>';

Upvotes: 2

Amit Rajput
Amit Rajput

Reputation: 2059

Use class name & index like below:

1st table :

$table1 = $html->find('table[class=nick]', 0); 

2nd table :

$table2 = $html->find('table[class=nick]', 1); 

Upvotes: 1

Related Questions