2010-06-24 79 views
1

我正在解析出一个HTML表并根据行值构建一个数组。我的问题是返回的关联键有一点空白在他们给我的最终结果是这样的:关联数组键中的空白PHP

Array ([Count ] => 6 [Class ] => 30c [Description] => Conformation Model (Combined 30,57)) 

所以这样一行:

echo $myArray['Count']; 

echo $myArray['Count ']; 

给了我一个空白的结果。

现在我已经有了一个相当哈克工作四处走动......

foreach($myArray as $row){ 

    $count = 0; 
    foreach($row as $info){ 
     if($count == 0){ 
      echo 'Count:' . $info; 
      echo '<br>'; 
     } 
     if($count == 1){ 
      echo ' Class:' . $info; 
      echo '<br>'; 
     } 
     if($count == 2){ 
      echo ' Description:' . $info; 
      echo '<br>'; 
     } 
     $count++; 
    } 

}

我使用的解析,我发现here表功能:

function parseTable($html) 
{ 
    // Find the table 
    preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html); 

    // Get title for each row 
    preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches); 
    $row_headers = $matches[1]; 

    // Iterate each row 
    preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches); 

    $table = array(); 

    foreach($matches[1] as $row_html) 
    { 
    preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches); 
    $row = array(); 
    for($i=0; $i<count($td_matches[1]); $i++) 
    { 
     $td = strip_tags(html_entity_decode($td_matches[1][$i])); 
     $row[$row_headers[$i]] = $td; 
    } 

    if(count($row) > 0) 
     $table[] = $row; 
    } 
    return $table; 
} 

我假设我可以通过更新正确的正则表达式来消除空白空间,但是,当然,我避免了像鼠疫这样的正则表达式。有任何想法吗?提前致谢。 -J

+1

任何具体的原因,为什么你不直接解析HTML使用这样一个解析器? http://simplehtmldom.sourceforge.net/ – 2010-06-24 18:48:13

+0

我有一个非常具体的原因...从来没有听说过它直到现在;)感谢您指出它。 – 2010-06-24 18:52:34

回答

4

您可以使用trim除去开头和结尾的空白字符:

$row[trim($row_headers[$i])] = $td; 

但不要用正则表达式解析HTML文档;改用Simple HTML DOM ParserDOMDocument等合适的HTML解析器。

1

一个简单的方法是改变

$row[$row_headers[$i]] = $td; 

到:

$row[trim($row_headers[$i])] = $td;