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 解析用に設計されており、タグの最初と 2 番目の子を解析できる可能性があります。

于 2012-09-17T09:51:10.310 に答える