2011-02-01 37 views
0

我刚开始尝试自学PHP并需要一些帮助。使用DOM,我试图解析一个HTML表格,将结果放入MySQL数据库,但遇到问题。 我能够呼应表的每一行与此:从解析的HTML表格构建数组

foreach ($html->find('table') as $table) 
foreach ($table->find("tr") as $rows) 
    echo $rows."<br />"; 

的数据具有这样的结构:

<tr> 
<a href=http://some link>text1</a> 
<td class="...">text2</td> 
<td class="...">text3</td> 
<td class="...">text4</td> 
</tr> 

我试图得到该链接,text1-4到一个数组,但无法弄清楚。任何帮助,将不胜感激。 - 编辑 -
这是我试图分解的表格布局。

<tr> 
<th class="school first"> 
    <ahref="/local/team/home.aspx?schoolid=472d8593">Aberdeen</a> 
</th> 
<td class="mascot">Bulldogs</td> 
<td class="city">Aberdeen</td> 
<td class="state last">MS</td> 
</tr> 

jnpcl的回答给了我这个

ROW 
    TEXT: Bulldogs 
    TEXT: Aberdeen 
    TEXT: MS 

,但没有联系。我原来的问题可能不够具体,但正如我所说,我正在努力学习,而且通常是通过在游泳池的深处跳跃来做到这一点。

+0

是您的HTML格式实际上这种方式?你的``元素不在实际的表格单元内... – drudge 2011-02-01 18:33:41

+0

DOM是什么?那不是内置的`DomDocument`或`SimpleXML`? – ircmaxell 2011-02-01 18:49:32

回答

2

更新:现在应该使用OP的更新示例代码。

这应该让你去:

表array.php

<?php 
    // SimpleHTMLDom Library 
    require_once('lib/simple_html_dom.php'); 

    // Source Data 
    $source = 'table-array-data.htm'; 

    // Displays Extra Debug Info 
    $dbg = 1; 

    // Read DOM 
    $html = file_get_html($source); 

    // Confirm DOM 
    if ($html) { 
     // Debug Output 
     if ($dbg) { echo '<pre>'; } 

     // Loop for each <table> 
     foreach ($html->find('table') as $table) { 

      // Debug Output 
      if ($dbg) { echo 'TABLE' . PHP_EOL; } 

      // Loop for each <tr> 
      foreach ($table->find('tr') as $row) { 

       // Debug Output 
       if ($dbg) { echo ' ROW' . PHP_EOL; } 

       // Loop for each <th> 
       foreach ($row->find('th') as $cell) { 

        // Look for <a> tag 
        $link = $cell->find('a'); 

        // Found a link 
        if (count($link) == 1) { 

         // Debug Output 
         if ($dbg) { echo '  LINK: ' . $link[0]->innertext . ' (' . $link[0]->href . ')' . PHP_EOL; } 
        } 

       } 

       // Loop for each <td> 
       foreach ($row->find('td') as $cell) { 

        // Debug Output 
        if ($dbg) { echo '  CELL: ' . $cell->innertext . PHP_EOL; } 
       } 
      } 
     } 
     // Debug Output 
     if ($dbg) { echo '</pre>'; } 
    } 
?> 

table_array_data.htm

<table> 
    <tr class="first"> 
     <th class="school first"><a href="/local/team/home.aspx?schoolid=472d8593-9099-4925-81e0-ae97cae44e43&amp">Aberdeen</a></th> 
     <td class="mascot">Bulldogs</td> 
     <td class="city">Aberdeen</td> 
     <td class="state last">MS</td> 
    </tr> 
</table> 

输出

TABLE 
    ROW 
     LINK: Aberdeen (/local/team/home.aspx?schoolid=472d8593-9099-4925-81e0-ae97cae44e43&) 
     CELL: Bulldogs 
     CELL: Aberdeen 
     CELL: MS