致命错误:在null上调用成员函数getElementsByTagname()

时间:2017-09-19 04:38:56

标签: php

if ($rows->length > 0) 
   {
     for ($i=1; $i<=$rows->length ; $i++) 
     {
        //echo($rows[$i]->getElementsByTagname('th'));
        $cols = $rows->item($i)->getElementsByTagname('td');
        for ($j=0; $j <$cols->length ; $j++) 
        { 
          //echo($cols[$j]->nodeValue);
          $input_lines = $cols[$j]->nodeValue;
          $input_lines =  preg_replace("/\D/", "", $input_lines);
          echo $input_lines;
          echo"<br><br>";

        }     
      }
    }
  

致命错误:在null上调用成员函数getElementsByTagname()

2 个答案:

答案 0 :(得分:0)

方法getElementsByTagName可能返回NULL(根据文档here),因此您需要检查非null变量:

$cols = $rows->item($i)
if( !null($cols)){
  $cols = $cols->getElementsByTagname('td')
}
else {
    throw new Exception("Element with name 'some name' was not found");
}

答案 1 :(得分:0)

对我来说更好的作品:$cols = $items->item($i); if($cols != NULL) {...