2013-10-27 30 views
1

我有这样的错误:使用DOM PHP获取从表中的HTML数据

Error Trying to get property of non-object 

而且代码:

$dom->preserveWhiteSpace = false; 

    $tables = $dom->getElementsByTagName('table'); 

    $rows = $tables->item(0)->getElementsByTagName('tr'); 

    $i=0; 
    foreach ($rows as $row) 
    { 
     /*** get each column by tag name ***/ 
     $cols = $row->getElementsByTagName('td'); 

     $this->data['Table'][$i] = array(
          'Attrb1' => $cols->item(0)->nodeValue, 
          'Attrib2' => $cols->item(1)->nodeValue 

           ); 
    $i++; 

    } 
     } 

     return $this->toArray(); 
    } 

,我有这个错误是行:

'Attrib2' => $cols->item(1)->nodeValue 

的HTML代码是:

<table border=1 align="center" cellpadding=5 width="95%"> 
              <!doctype html public "-//w3c//dtd html 4.0//EN"> 
<html it> 
<head> 
<meta name="Generator" content="OLS"> 
</head> 
<body> 
<td colspan=2 align="center"> 
<b> 
<i> 
Attrib1 
</i> 
</b> 
</td> 
<td> 
<b> 
<i> 
Attrib2 
</i> 
</b> 
</td> 
<td> 
<b> 
<i> 
<tr> 
<td> 
A000211 
</td> 
<td nowrap> 
Statistic 
</td> 
</tr> 

但我不知道如果问题是在foreach或所有得到的数据,我所做的是一个大错误,或者我以错误的方式处理html ..所以帮我请..

+0

错误提示该行中没有两个TD。 - 这对于HMTL的快速扫描显示了一些不规则的情况,可以在加载时进行纠正,这是有道理的。 - 请将您的问题隔离为您从头创建的示例,其中包含尽可能少的数据和代码以证明您的问题。此外,我建议创建一个HTML表格模型来处理表格,以便您可以更轻松地访问行和列。 – hakre

+0

不是TD的是8但仍然如果我尝试把所有我有这个错误..我不能改变HTML。 – FelasDroid

+0

行的一个例子是:​​ 远程信息 04/09/2012 2011/2012 ​​ 检查 2008/2009 – FelasDroid

回答

2

你可以使用:

$dom->loadHTML($result); 
libxml_clear_errors(); 
libxml_use_internal_errors($errors); 
/*** discard white space ***/ 
$dom->preserveWhiteSpace = false; 
/*** the table by its tag name ***/ 
$tables = $dom->getElementsByTagName('table'); 
/*** get all rows from the table ***/ 
$rows = $tables->item(1)->getElementsByTagName('tr'); 
/*** loop over the table rows ***/ 
$i=0; 
foreach ($rows as $row) { 
    /*** get each column by tag name ***/ 
    $cols = $row->getElementsByTagName('td'); 

    $this->data['List'][$i] = array(
     'name1' => $cols->item(1)->nodeValue, 
     'name2' => $cols->item(2)->nodeValue, 
     'name3' => $cols->item(3)->nodeValue, 
     'name4' => $cols->item(4)->nodeValue, 
     'name5' => $cols->item(5)->nodeValue, 
     'name6' => $cols->item(6)->nodeValue, 
     'name7' => $cols->item(7)->nodeValue 
    ); 
    $i++; 
}