php 将 dom 元素的一部分转换为字符串,其中包含 html 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4530504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:20:47  来源:igfitidea点击:

convert part of dom element to string with html tags inside of them

phphtmldom

提问by dakshina11

im in need of converting part of DOM element to string with html tags inside of them.

我需要将 DOM 元素的一部分转换为字符串,其中包含 html 标签。

i tried following but it prints just a text without tags in side.

我试过跟随,但它只打印了一个没有标签的文本。

$dom = new DOMDocument();
$dom->loadHTMLFile('http://www.pixmania-pro.co.uk/gb/uk/08920684/art/packard-bell/easynote-tm89-gu-015uk.html');
$xpath = new DOMXPath($dom);
$elements=xpath->query('//table');

foreach($elements as $element)
echo $element->nodeValue;

i want all the tags as it is and the content inside tables. can some one help me. it'll be a greate help.

我想要所有的标签和表格中的内容。有人能帮我吗。这将是一个很大的帮助。

thanks.

谢谢。

回答by dev-null-dweller

Current solution:

当前解决方案

foreach($elements as $element){
    echo $dom->saveHTML($element);
}

Old answer (php < 5.3.6):

旧答案(php < 5.3.6):

  1. Create new instance of DomDocument
  2. Clone node (with all sub nodes) you wish to save as HTML
  3. Import cloned node to new instance of DomDocument and append it as a child
  4. Save new instance as html
  1. 创建 DomDocument 的新实例
  2. 您希望保存为 HTML 的克隆节点(包含所有子节点)
  3. 将克隆的节点导入 DomDocument 的新实例并将其附加为子节点
  4. 将新实例另存为 html

So something like this:

所以像这样:

foreach($elements as $element){
    $newdoc = new DOMDocument();
    $cloned = $element->cloneNode(TRUE);
    $newdoc->appendChild($newdoc->importNode($cloned,TRUE));
    echo $newdoc->saveHTML();
}

回答by dennis

With php 5.3.6 or higher you can use a node in DOMDocument::saveHTML:

使用 php 5.3.6 或更高版本,您可以使用DOMDocument::saveHTML 中的节点:

foreach($elements as $element){
    echo $dom->saveHTML($element);
}