php 如何从 DOMXPath::query() 方法获取完整的 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17012395/
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 12:05:23  来源:igfitidea点击:

How to get full HTML from DOMXPath::query() method?

phpdomdocument

提问by Milo? ?akonovi?

I have document from which I want to extract specific div with it's untouched content. I do:

我有一个文档,我想从中提取特定 div 的未修改内容。我愿意:

$dom = new DOMDocument();
$dom->loadHTML($string);//that's HTML of my document, string

and xpath query:

和 xpath 查询:

$xpath = new DOMXPath($dom);
$xpath_resultset =  $xpath->query("//div[@class='text']");
/*I'm after div class="text"*/

now I do item(0)method on what I get with $xpath_resultset

现在我做item(0)我得到的方法$xpath_resultset

$my_content = $xpath_resultset->item(0);

what I get is object (not string) $my_content which I can echo or settype() to string, but as result I get is with fully stripped markup?

我得到的是对象(不是字符串)$my_content,我可以将其回显或 settype() 到字符串,但结果我得到的是完全剥离的标记?

What to do to get allfrom div class='text' here?

如何从 div class='text'获取所有内容?

回答by Tim Cooper

Just pass the node to the DOMDocument::saveHTMLmethod:

只需将节点传递给DOMDocument::saveHTML方法:

$htmlString = $dom->saveHTML($xpath_resultset->item(0));

This will give you a string representation of that particular DOMNode and all its children.

这将为您提供该特定 DOMNode 及其所有子节点的字符串表示。