在我的案例页面中,多个table
具有相同的类,因此我在tr, td and plaintext
的帮助下找到了价值。
PHP部分:
$html = file_get_html('http://www.example.com/');
$eles = $html->find('.info-tab');
foreach($eles as $e) {
if(strpos($e->find('tr',0)->plaintext, "Information about the manufacturer and the model." ) ) {
$value1 = $e->find('td',1)->plaintext;
}
if(strpos($e->find('tr',1)->plaintext, "Information about the manufacturer and the model." ) ) {
$value2 = $e->find('td',1)->plaintext;
}
}
echo $value1;
echo $value2;
网页
// Here's will be many other "Table" with diffrent text but class & ID are same...
<table class="info-tab">
<tbody>
<tr>
<td>Information about the manufacturer and the model.</td>
<td>1000</td>
</tr>
<tr>
<td>dummy text</td>
<td>dummy text</td>
</tr>
</tbody>
</table>
// Here's will be many other "Table" with diffrent text but class & ID are same...
<table class="info-tab">
<tbody>
<tr>
<td>dummy text</td>
<td>dummy text</td>
</tr>
<tr>
<td>Information about the manufacturer and the model.</td>
<td>3000</td>
</tr>
<tr>
<td>dummy text</td>
<td>dummy text</td>
</tr>
</tbody>
</table>
// Here's will be many other "Table" with diffrent text but class & ID are same...
页面有多个表20加号,只有两个表具有此文本,所以我想复制它们。
如何找到这两个值?
答案 0 :(得分:1)
您应该迭代表,并为每个表迭代行:
$token = "Information about the manufacturer and the model.";
$tables = $html->find('.info-tab');
$values = [];
foreach ($tables as $table) {
foreach ($table->find('tr') as $row) {
if (strpos($row->find('td', 0)->plaintext, $token) !== false) {
$values [] = $row->find('td', 1)->plaintext;
}
}
}
var_dump($values);
您的代码不起作用,因为$e->find('td', 1)
始终是表中第一行的第二个td(并且不考虑所选的行0或1)。