2
我想弄清楚为什么这段代码不工作。它从代码的另一部分获取HTML,将表从中取出,创建另一列并尝试将td元素移动到新创建列中的上一行。PHP的DOM HTML表操作
表输入:
+-------------------+-------------------+-------------------+
| Existing column1 | Existing column2 | Existing column3 |
+-------------------+-------------------+-------------------+
| A | B | C |
| D | E | F |
| G |
+-------------------+-------------------+-------------------+
我想尝试,并使它看起来像这样:
+-------------------+-------------------+-------------------+-------------+
| Existing column1 | Existing column2 | Existing column3 | New column1 |
+-------------------+-------------------+-------------------+-------------+
| A | B | C | |
| D | E | F | G |
+-------------------+-------------------+-------------------+-------------+
因此,只要td
元素具有类text-info
,它移动起来一个tr
和附加到最后Comment
列
我的代码到目前为止:
$dom = new DOMDocument();//Loads DOM document
$dom->loadHTML($str);//Loads HTML from a previously set variable
$xpath = new DOMXPath($dom);
$tables = $xpath->query('//table[@class="behaviourtable table"]');//Get only table from HTML
$commsTable = '';
foreach ($tables as $table) {
$commsTable .= $dom->saveXML($table);
}
$commsHTML = new DOMDocument();
$commsHTML->loadHTML($commsTable);
$tr = $commsHTML->getElementsByTagName('tr');
$th = $commsHTML->createElement('th', 'Comment');
$tr->item(0)->appendChild($th);
$xpathcomms = new DOMXPath($commsHTML);
$comments = $xpathcomms->query('//td[@class="text-info"]');
if($comments->length > 0){
echo "if running";
foreach($comments as $comment){
$parent = $comment->parentNode;
$parent->appendChild($comment);
$commsHTML->saveXML($parent);
}
}
echo $commsHTML->saveHTML();
我觉得'$ tables'没有任何结果。由于类名不能包含空格,但是您使用了[[class =“behaviourtable table”]' – Mohammad
@Mohammad代码运行到'$ xpathcomms = new DOMXPath($ commsHTML);'行。 '$ tables'肯定会返回带有新列'Comments'的HTML表格。 –
php是否会返回任何错误? – Mohammad