gpt4 book ai didi

php - 如何防止文档类型被添加到 HTML 中?

转载 作者:搜寻专家 更新时间:2023-10-31 20:51:40 26 4
gpt4 key购买 nike

我一直在用 DOM 处理这个 tidy-up-messy-html 标签,但现在我意识到一个更大的问题,

$content = '<p><a href="#">this is a link</a></p>';

function tidy_html($content,$allowable_tags = null, $span_regex = null)
{
$dom = new DOMDocument();
$dom->loadHTML($content);

// other codes
return $dom->saveHTML();
}

echo tidy_html($content);

它将输出整个DOM,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body><p><a href="#">this is a link</a></p></body></html>

但我只想要这样的返回,

<p><a href="#">this is a link</a></p>

我不想,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body>...</body></html>

这可能吗??

编辑:

innerHTML 模拟在我的数据库中生成了一些奇怪的代码,比如 '

<p>Monday July 5th 10am - 3.30pm £20</p>&#13;
<p>Be one of the first visitors to the ...at this special event.Â</p>&#13;
<p>All participants will receive a free copy of the ‘Contemporary Art Kit’ produced exclusively for Art on....</p>&#13;

innerHTML模拟,

$innerHHTML = '';
$nodeBody = $dom->getElementsByTagName('body')->item(0);
foreach($nodeBody->childNodes as $child) {
$innerHTML .= $nodeBody->ownerDocument->saveXML($child);
}

我发现它在中断时创建奇怪代码的原因是由 saveXML($child)

所以当我遇到这样的事情时,

$content = '<p><br/><a href="#">xx</a></p>
<p><br/><a href="#">xx</a></p>';

它会返回这样的东西,

<p><a href="#">xx</a></p>&#13;
<p><a href="#">xx</a></p>

但我其实想要这样的东西,

<p><a href="#">xx</a></p>
<p><a href="#">xx</a></p>

最佳答案

如果您正在处理一个片段,您通常只需要正文内容。

PHP 中的 DomDocument 不提供类似 innerHTML 的东西。但是你可以模拟它:

$innerHHTML = '';
$nodeBody = $dom->getElementsByTagName('body')->item(0);
foreach($nodeBody->childNodes as $child) {
$innerHTML .= $nodeBody->ownerDocument->saveXML($child);
}

如果你只想修复一个片段,你可以使用 tidy library还有:

$html = tidy_repair_string($html, array('output-xhtml'=>1,'show-body-only'=>1));

关于php - 如何防止文档类型被添加到 HTML 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6851620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com