用新的html值替换td单元格文本


Replace td cell text with new html value

我试图替换所有的td单元格文本包括链接标签。目前使用下面的代码,单元格被替换,但当我输出表格时,它实际上只是输出html代码,如下所示:

<a href="sdf" class="link">Some text</a>

而不是真正的物理HTML链接。我如何用HTML标签实际替换nodeValue ?谢谢。

$DOM = new DOMDocument( );
@$DOM->loadHTML( $htmlTable );
$DOMXPath = new DOMXPath( $DOM );
$cellName = $DOMXPath->query('//td[contains(@class,"classA")]');
foreach( $cellName as $text ) {
    $text->nodeValue = '<a href="sdf" class="link">' . htmlspecialchars( trim( $text->nodeValue ) ) . '</a>';
}

终于成功了。以防对谁有帮助。要使用td值内的HTML更改文本节点,请使用以下命令:

$partial = $DOM->createDocumentFragment();
$partial->appendXML('<a href="sdf" class="link">some text</a>');
$text->parentNode->replaceChild($partial, $text );