我刚刚开始尝试自学PHP并需要一点帮助。使用DOM,我试图解析一个HTML表格,将结果放入MySQL dbase,但是遇到了问题。 我可以用这个回显表格的每一行:
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 :(得分: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&">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