2012-09-16 66 views
1

我有一个简单的html文件,其中包含此内容。如何迭代文件中的数组

<table border="1"> 
    <tr> 
     <td>Name</td> 
     <td>City</td> 
    </tr> 
    <tr> 
     <td>Greg House</td> 
     <td>Century City</td> 
    </tr> 
    <tr> 
     <td>Dexter Morgan</td> 
     <td>Miami</td> 
    </tr> 
</table> 

我有这样的脚本:

include_once('simple_html_dom.php'); 

//$html = file_get_html(''); 
$html = file_get_html('http://localhost/path2mylocalfile/test1.html'); 

// first check if $html->find exists 
if (method_exists($html,"find")) 
{ 
    // then check if the html element exists to avoid trying to parse non-html 
    if ($html->find('html')) 
    { 

     foreach ($html->find('table') as $table) 
     { 

      // loop over rows 
      foreach($table->find('tr') as $row) 
      { 
       // initialize array to store the cell data from each row 
       $rowData = array(); 

       foreach($row->find('td.text') as $cell) 
       { 
        // initialize array to store the cell data from each col 
        //$colData = array();     

        // push the cell's text to the array 
        $rowData[] = $cell->innertext; 
       } 

       if ($rowData) $theData[]=$rowData; 

      } 
      //print_r($theData);   

     } 
    } 
} 

//Show array  
//foreach ($colData as $colItems) 
//{ 
     foreach ($rowData as $rowItems) 
      { 
       echo "$rowItems<br /><br />"; 
      } 
      //print_r($theData); 
//} 

如果我只用$rowData环路我只得到了姓氏和城市了,所以我试图添加$colData循环,但是当我使用这个不会出现在屏幕上。

如何循环遍历行和列并显示名称和城市?

+0

尝试使用XML,然后用PHP解析它。 – AdamGold

+0

你的意思是你想输出'$ theData'中的每个城市吗? – Passerby

回答

0

您可以使用本地PhP函数DOMDocument-> loadHTML(http://docs.php.net/manual/en/domdocument.loadhtml.php)。

它专为HTML解析而设计,您可能会解析标签的第一个和第二个子元素。