我有一个问题的代码工作在一个PHP安装和不工作在另一个。当出现错误时,也许一次安装更容易原谅。
当我上传到生产环境时,我收到以下错误:
PHP Fatal error: Call to undefined method DOMText::getElementsByTagName() in ...
导致错误的行是:
$tds = $tr->getElementsByTagName('td');
我有一种感觉,这个问题与从DOMText::
而不是DOMDocument::
内部调用getElementsByTagName
方法有关(文档似乎使这一点显而易见),但由于我对我做错了什么缺乏理解,我不确定如何解决这个问题。
下面是我的代码:
<?php
// The HTML
$table_html = '<table>
<thead>
<tr>
<td>AAA</td>
<td>BBB</td>
</tr>
</thead>
<tbody>
<tr>
<td>aaa</td>
<td>bbb</td>
</tr>
</tbody>
</table>';
// Create DOM Document
$document = new DOMDocument();
$document->preserveWhiteSpace = false;
$document->formatOutput = true;
@$document->loadHTML($table_html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOEMPTYTAG);
// Change TD's to TH's in THEAD's
$theads = $document->getElementsByTagName('thead')->item(0);
if ($theads) {
foreach($theads->childNodes AS $tr) {
$tds = $tr->getElementsByTagName('td'); // <---- This is where the error occurs
if ($tds->length > 0) {
$i = $tds->length - 1;
while($i > -1) {
$td = $tds->item($i); // td
$text = $td->nodeValue; // text node
$th = $document->createElement('th', $text); // th element with td node value
$td->parentNode->replaceChild($th, $td); // replace
$i--;
}
}
}
}
// Output
echo $document->saveHTML();
问题是,childNodes
在每个标记之间包含空白文本节点。
要在$theads
中获得<tr>
标签,请使用getElementsByTagName
,例如
foreach ($theads->getElementsByTagName('tr') as $tr) {
// ...
}
或者,如果您需要第一个<thead>
中的所有<td>
元素,请尝试使用XPath
$xpath = new DOMXPath($document);
$tds = $xpath->query('//thead[1]/tr/td'); // xpath indexes are 1-based