简体   繁体   English

DOMDocument使用额外的标签保存html

[英]DOMDocument saving html with extra tags

I am using HTMLDom to manipulate a string, rather than a complete webpage. 我正在使用HTMLDom操作字符串,而不是完整的网页。 When I use saveHTML() it automatically throws in doctype and html tags. 当我使用saveHTML()它会自动抛出doctypehtml标签。

$str = 'frament containing html';
$str = utf8_encode($str);
$doc->LoadHTML($str);
...do stuff...
$str = $doc->saveHTML();

What is the correct way to save a fragment of HTML without the automatic inclusion of extra tags. 在不自动包含额外标签的情况下,保存HTML片段的正确方法是什么。 Failing that; 失败了; the correct method to remove these extra tags? 删除这些多余标签的正确方法?

I used an html parser to avoid using regex's , so it seems a little counter-intuitive to have to use them on the output of a parser. 我使用html解析器来避免使用regex ,因此不得不在解析器的输出上使用它们似乎有点违反直觉。

PHPs DOMDocument repairs the document if you load HTML. 如果加载HTML,PHPs DOMDocument会修复文档。 That means it adds the html and body elements. 这意味着它将添加htmlbody元素。

So you need to fetch all nodes inside body and save them as HTML. 因此,您需要获取body内的所有节点并将其另存为HTML。

$html = <<<'HTML'
<h1>Hello World</h1>
Text
<!-- comment -->
HTML;

$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXPath($dom);

$result = '';
foreach ($xpath->evaluate('/html/body/node()') as $node) {
  $result .= $dom->saveHtml($node);
}

echo $result;

Here is another option, but it is not available everywhere yet. 这是另一种选择,但并非在所有地方都可用。 PHP added LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD options. PHP添加了LIBXML_HTML_NOIMPLIEDLIBXML_HTML_NODEFDTD选项。

$dom->loadHtml($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

PHP <= 5.3 PHP <= 5.3

The first an best option would be to update the PHP. 首先,最好的选择是更新PHP。 PHP 5.3 is no longer maintained. 不再维护PHP 5.3。

The second option is using DOMDocument::saveXML($node, LIBXML_NOEMPTYTAG). 第二个选项是使用DOMDocument :: saveXML($ node,LIBXML_NOEMPTYTAG)。 This will generate an XML (XHTML) fragment, but should be enough for the most cases. 这将生成一个XML(XHTML)片段,但对于大多数情况来说应该足够了。

The last option would be using the string functions. 最后一个选择是使用字符串函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM