【问题标题】:Need advice on parsing an html table with PHP需要有关使用 PHP 解析 html 表的建议
【发布时间】:2013-01-14 15:59:21
【问题描述】:

我正在使用这个问题来解决这个问题。 How to parse this table and extract data from it?

但是在我试图解析的表格上被难住了。

这是PHP页面源代码。 里面只有一张表,表 id 为“troops”。

我设法在数组中获取表头,但无法将行数据与表头连接起来。

这是我正在使用的代码,它用于上面的文章,根据我的需要进行了编辑。

html 源代码 http://pastebin.com/RKbzVT1V

使用的php代码

$content = $_POST['src'];
$dom = new DomDocument;
$dom -> loadHtml($content);

$xpath = new DomXPath($dom);

// collect header names

$headerNames = array();
foreach ($xpath->query('//table[@id="troops"]//th') as $node) {
//foreach ($xpath->query('//th[ contains (@class, "vil fc") ]') as $node) {
    $headerNames[] = $node -> nodeValue;

}

// collect data

$data = array();
foreach ($xpath->query('//tr') as $node) {
    $rowData = array();
    foreach ($xpath->query('//td', $node) as $cell) {
        $rowData[] = $cell -> nodeValue;
    }

    $data[] = array_combine($headerNames, $rowData);
}

感谢您对此事的任何帮助,如果有更简单的方法,请提出建议。

【问题讨论】:

  • “无法将行数据与标题连接”是什么意思?你实际得到什么输出,你想得到什么输出?
  • 第一行是否包含每个后续行中每个 th+td 需要匹配的标题?

标签: php arrays parsing html-table


【解决方案1】:

运行你的代码我得到:

PHP 警告:array_combine():两个参数应该有相同数量的元素

这意味着$headerNames 中的项目数不等于$rowData 中的项目数。您的 $rowData 包含一行的所有 TD 元素,但如果您查看 HTML,您会发现 TD 元素比 TH 元素多:

<tr class="hover">
 <th class="vil fc">
     <a href="build.php?newdid=3665&id=39#td">00 La piu …</a>
 </th>
 <td>54</td>
 <td>5</td>
 <td class="none">0</td>
 <td>74</td>
 <td>355</td>
 <td class="none">0</td>
 <td class="none">0</td>
 <td class="none">0</td>
 <td class="none">0</td>
 <td class="none">0</td>
 <td class="none lc">0</td>
</tr>

我假设您正在尝试实现这样的目标:

[00 La piu …] => Array
    (
        [0] => 54
        [1] => 5
        [2] => 0
        [3] => 74
        [4] => 355
        [5] => 0
        [6] => 0
        [7] => 0
        [8] => 0
        [9] => 0
        [10] => 0
    )

下面的代码会产生什么:

libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTMLFile('NewHTMLFile.html');
$table = $dom->getElementById('troops');
foreach ($table->getElementsByTagName('tr') as $tr) {
    if ($header = $tr->getElementsByTagName('th')->item(0)) {
        $data[trim($header->nodeValue)] = array_map(
            function(DOMElement $td) { return $td->nodeValue; },
            iterator_to_array($tr->getElementsByTagName('td'))
        );
    }
}
libxml_use_internal_errors(false); 
print_r($data);

如果这不是您要查找的内容,请更新您的问题并包含您尝试获得的输出示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多