如何按列而不是按行(使用 DOMDocument / DOMXPath)解析 html 表 td?意思是根据它所在的表的列解析一个 td 元素,而不是它在哪个 tr 中?
问问题
1032 次
1 回答
2
HTML 表格按行分组,而不是按列分组。最好的办法是迭代行并将行分配给适当的数组,通过键同步。
例子:
<?php
$html = <<<HTML
<table id="target">
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
</tr>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
</tr>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
</tr>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
</tr>
</table>
HTML;
$document = new DOMDocument();
$document->loadHTML($html);
$table = $document->getElementById("target");
$tr_list = $table->getElementsByTagName("tr");
$tr_count = 0;
$columns = array();
foreach ($tr_list as $tr) {
/** @var $tr DOMElement */
$td_list = $tr->getElementsByTagName("td");
$tr_count++;
$td_count = 0;
foreach ($td_list as $td) {
$columns[$tr_count][$td_count] = $td;
$td_count++;
}
}
print_r($columns);
于 2012-06-25T16:15:50.080 回答