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循环,但是当我使用它时,屏幕上什么也没有。

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

4

1 回答 1

0

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

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

于 2012-09-17T09:51:10.310 回答