HTML 代码在页面中显示为源代码,而不是由浏览器执行


html code appear in the page as source and not executed by browser

我的代码是这样的:

$link = "<a class='"openevent'" href='"$finalUrl'" target='"_blank'">Open Event</a>";
foreach ($spans as $span) {
if ($span->getAttribute('class') == 'category') {
$span->nodeValue .= $link;
    }
}

这里的问题是$link变量在页面中作为 HTML 源回显,如下所示

<a class="openevent" href="http://www.mysite.com/Free-Live-Streaming-Video-Online-Other-Cycling-Cycling-The-Tour-of-Britain-170638.html" target="_blank">Open Event</a>

而不是像往常一样显示超链接

我的代码有什么问题?

您正在向跨度的节点值添加文本,要添加锚节点,您必须创建一个具有createElement的锚节点,并向其中添加属性,然后将其附加到跨度。


foreach ($spans as $span) {
    if ($span->getAttribute('class') == 'category') {    
        $link = $doc->createElement('a', 'Open Event');
        $link->setAttribute("class", "openevent");
        $link->setAttribute("href", $finalUrl);
        $link->setAttribute("target", "_blank");
        $span->appendChild($link);
    }
}

看起来你正在 foreach 中构建某种 xml。 当您构建 XML 时,它将 HTML 字符"<"编码为 &mp;gt; 因此在打印时,您实际上不会打印 HTML。 可能是html_entity_decode功能将为您工作。

echo html_entity_decode($doc->saveHTML())