这下面的代码工作没有任何问题,但移动到功能后我得到错误,并没有工作
Route::get('test', ['as' => 'test', function () {
$data = 'MYURL';
$table = [];
$html = new \Htmldom($data);
foreach($html->find('tr') as $row) {
$col_1 = $row->find('td',0)->plaintext;
$col_2 = "";
try{
$col_2= $row->find('td',1)->plaintext;
}catch (Exception $ignore){}
$table[] = $col_2;
}
$values = array_values($table);
unset($values[0]);
unset($values[1]);
unset($values[5]);
$values = array_values($values);
print_r($values);
/*print_r(\App\Customs\Helpers::get_online_currencies());*/
}]);
我的班级:
class Helpers
{
public static function get_online_currencies(){
$data = 'MYURL';
$table = [];
$html = new \Htmldom($data);
foreach($html->find('tr') as $row) {
$col_2 = "";
try{
$col_2= $row->find('td',1)->plaintext;
}catch (Exception $ignore){}
$table[] = $col_2;
}
$values = array_values($table);
unset($values[0]);
unset($values[1]);
unset($values[5]);
return array_values($values);
}
}
错误:
ErrorException in Helpers.php line 23:
Trying to get property of non-object
第23行:
$col_2= $row->find('td',1)->plaintext;
您可以测试我的代码。
答案 0 :(得分:2)
第一行和最后一行只有一列。在获取数据之前断言find
的结果:
foreach($html->find('tr') as $row) {
$col_2 = "";
try{
$col_2= $row->find('td',1);
}catch (Exception $ignore){}
$table[] = $col_2 ? $col_2->plaintext : "";
}