简体   繁体   English

如何在PHP中按类名获取HTML表格元素

[英]how to get html table element by classname in php

Here is a table whose classname is nick. 这是一个表,其类名是nick。 I am trying to get this table by class name "nick". 我正在尝试通过类名称“ 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". 我怎样才能按尼克及其行和列的类来获取此表。另外还有2个表的类名为“尼克”。

You forgot to put the index inside ->find() . 您忘记了将索引放在->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. 当您放置索引(在本例中为0 )时,您将指向该类的第一个找到的元素。

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

Reference: 参考:

mixed find ( string $selector [, int $index] ) 混合查找(字符串$ selector [,int $ index])

Find elements by the CSS selector. 通过CSS选择器查找元素。 Returns the Nth element object if index is set, otherwise return an array of object. 如果设置了索引,则返回第N个元素对象,否则返回对象数组。

Of course, the first table falls under zero index ( 0 ), the second on one ( 1 ). 当然,第一个表属于零索引( 0 ),第二个表属于一个( 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: 如果要加倍努力,可以先检查是否存在未使用->find()方法更改该类名称的表:

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

You can get right html using class in php like below code. 您可以使用以下代码在php中使用类来获取正确的html。

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>';

Use class name & index like below: 使用类名和索引,如下所示:

1st table : 第一张桌子:

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

2nd table : 第二表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM