需要有关使用PHP解析html表的建议

时间:2013-01-30 18:06:01

标签: php arrays parsing html-table

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

但是我正在努力解析桌子上的问题。

这是PHP页面源代码。 其中只有一张桌子,桌子名为“部队”。

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

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

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);
}

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

1 个答案:

答案 0 :(得分:2)

运行我的代码:

  

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);

如果这不是您想要的,请更新您的问题,并提供您想要获得的输出样本。

相关问题