为了账号安全,请及时绑定邮箱和手机立即绑定

如何在没有HTML包装的情况下保存DOMDocument的HTML?

如何在没有HTML包装的情况下保存DOMDocument的HTML?

PHP
饮歌长啸 2019-07-09 14:16:26
如何在没有HTML包装的情况下保存DOMDocument的HTML?我是下面的函数,我很难输出DOMDocument而没有附加XML,HTML,体体和p内容输出之前的标签包装。建议的解决办法:$postarray['post_content'] = $d->saveXML($d->getElementsByTagName('p')->item(0));只有当内容中没有块级元素时才能工作。但是,当它这样做时,如下面使用H1元素的示例所示,SaveXML的结果输出被截断为.<p>If you like</p>我被指出这篇文章是一种可能的解决办法,但我不明白如何将它实现到这个解决方案中(请参阅下面的注释)。有什么建议吗?function rseo_decorate_keyword($postarray) {     global $post;     $keyword = "Jasmine Tea"     $content = "If you like <h1>jasmine tea</h1> you will really like it with Jasmine Tea flavors.      This is the last ocurrence of the phrase jasmine tea within the content. If there are other instances of the      keyword jasmine tea within the text what happens to jasmine tea."     $d = new DOMDocument();     @$d->loadHTML($content);     $x = new DOMXpath($d);     $count = $x->evaluate("count(//text()[contains(translate(., 'ABCDEFGHJIKLMNOPQRSTUVWXYZ', 'abcdefghjiklmnopqrstuvwxyz'),      '$keyword') and (ancestor::b or ancestor::strong)])");     if ($count > 0) return $postarray;     $nodes = $x->query("//text()[contains(translate(., 'ABCDEFGHJIKLMNOPQRSTUVWXYZ', 'abcdefghjiklmnopqrstuvwxyz'), '$keyword')      and not(ancestor::h1) and not(ancestor::h2) and not(ancestor::h3) and not(ancestor::h4) and not(ancestor::h5) and not(ancestor::h6)      and not(ancestor::b) and not(ancestor::strong)]");     if ($nodes && $nodes->length) {         $node = $nodes->item(0);         // Split just before the keyword         $keynode = $node->splitText(strpos($node->textContent, $keyword));         // Split after the keyword         $node->nextSibling->splitText(strlen($keyword));         // Replace keyword with <b>keyword</b>         $replacement = $d->createElement('strong', $keynode->textContent);         $keynode->parentNode->replaceChild($replacement, $keynode);
查看完整描述

3 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

所有这些答案现在都是不对,因为PHP 5.4和Libxml 2.6loadHTML现在有一个$option参数,该参数指示Libxml如何解析内容。

因此,如果我们使用以下选项加载HTML

$html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

做时saveHTML()不会有doctype,不<html>,而不是<body>.

LIBXML_HTML_NOIMPLIED关闭隐含html/body元素的自动添加LIBXML_HTML_NODEFDTD防止在找不到默认的doctype时添加。

关于Libxml参数的完整文档是这里

(请注意,loadHTMLDocs说Libxml 2.6是必需的,但是LIBXML_HTML_NODEFDTD仅在Libxml 2.7.8和LIBXML_HTML_NOIMPLIED见Libxml 2.7.7)


查看完整回答
反对 回复 2019-07-09
?
慕容708150

TA贡献1831条经验 获得超4个赞

只需在加载了loadHTML()文档后直接删除节点:

# remove <!DOCTYPE $doc->removeChild($doc->doctype);           
# remove <html><body></body></html> $doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild);


查看完整回答
反对 回复 2019-07-09
  • 3 回答
  • 0 关注
  • 292 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信