我想从网页中提取几个表格并在我的页面中显示它们
我本来打算使用正则表达式来提取它们,但后来我看到了 DOMDocument 类 我在 stackoverflow 中查看过,似乎更干净,似乎所有问题都是关于获取内部文本或使用循环来获取 elements 的内部节点。我现在想知道如何通过 id 提取并打印 html 元素。
$html = file_get_contents("www.site.com");
$xml = new DOMDocument();
$xml->loadHTML($html);
$xpath = new DOMXPath($xml);
$table =$xpath->query("//*[@id='myid']");
$table->saveHTML(); // this obviously doesn't work
如何在我的页面上将 $table 显示或回显为实际的 html 表格?
最佳答案
首先,DOMDocument
有一个 getElementById()
方法,因此您的 XPath 是不必要的 - 尽管我怀疑这就是它的工作原理。
其次,为了获取标记片段而不是整个文档,您可以使用 DOMNode::C41N()
,所以你的代码将如下所示:
<?php
// Load the HTML into a DOMDocument
// Don't forget you could just pass the URL to loadHTML()
$html = file_get_contents("www.site.com");
$dom = new DOMDocument('1.0');
$dom->loadHTML($html);
// Get the target element
$element = $dom->getElementById('myid');
// Get the HTML as a string
$string = $element->C14N();
查看working example .
关于php - 使用 DOMDocument 通过 id 提取并打印 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225739/