我想使用PHP的DOMDocument来解析一个html表,所以我在每个表中使用foreach:foreach($ _ POST [&#39;比较&#39;]为$ value){}其中我嵌套下面的代码。所以从比较表中我想取每一行($ value),该值包含一个html表(<table> ...</table>
)。这是我要解析的表:
<table>
<tbody>
<tr>
<td >.....</td>
<td>....</td>
</tr>
<tr>
<td>....</td>
<td>.....</td>
</tr>
</tbody>
</table>
第二个代码是这样的,我为行创建了一个foreach,然后为每一行创建了一个索引($ i),在每一行中为另一个foreach创建了一个带有新索引($ j)的列,所以目的是像这样回显每一行的每一列(第一列 - 第一行,第二列 - 第一行,第一列 - 第二行,第二列 - 第二行......
foreach($_POST['comparison'] as $value) {
echo "<div id='primary' class='content-area'>";
var_dump($value); // check the type in the variable value
$dom = new DOMDocument;
$dom->loadHTML($value);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
foreach ($tables->getElementsByTagName('tr') as $element1) {
for ($i = 0; $i < $element1->length; $i++) {
echo $element1->item($i)->nodeValue . "\n";
foreach ($element1->getElementsByTagName('td') as $element2) {
for ($j = 0; $j < $element2->length; $j++) {
echo $element2->item($j)->nodeValue . "\n"; }
/* $value_spec[] = $element2->nodeValue + "<br>"; */
}
}
}
echo " </div><!-- content-area -->";
}
}
我按照错误的指示&#34;调用未定义的方法DOMNodeList :: getElementsByTagName()&#34;,这是添加item()以访问表的每个单元格,但错误仍然存在。如果有人可以提供帮助,我将不胜感激。
答案 0 :(得分:0)
$tables = $dom->getElementsByTagName ('table');
// At this point, if you are sure that you want the first table found, add
$table = $tables->item(0);
// Below working code, I don't undersatand what you do with that loops
foreach ($table->getElementsByTagName ('tr') as $tr) {
foreach ($tr->getElementsByTagName ('td') as $td) {
echo $td->nodeValue . "\n";
}
}
答案 1 :(得分:0)
试试这个,
<?php
$dom = new domDocument;
$dom->loadHTML($value);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$tr = $dom->getElementsByTagName('tr');
foreach ($tr as $element1) {
for ($i = 0; $i < count($element1); $i++) {
echo $element1->nodeValue . "\n";
foreach ($element1->getElementsByTagName('td') as $element2) {
for ($j = 0; $j < count($element2); $j++) {
echo $element2->nodeValue . "\n";
}
}
}
}