【发布时间】: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