PHP 使用 DOMDocument 从 URL 中以字符串形式检索内部 HTML


PHP retrieve inner HTML as string from URL using DOMDocument

我一直在挑选零碎的代码,你可以大致看到我想要做什么,显然这是行不通的,而且是完全错误的:

<?php
$dom= new DOMDocument();
$dom->loadHTMLFile('http://example.com/');
$data = $dom->getElementById("profile_section_container");
$html = $data->saveHTML();
echo $html;
?>

使用 CURL 调用,我能够检索文档 URL 源:

function curl_get_file_contents($URL)
{
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
$f = curl_get_file_contents('http://example.com/'); 
echo $f;

那么我现在如何使用它在 PHP 中实例化 DOMDocument 对象并使用 getElementById 提取节点

这是避免任何格式错误的 HTML 错误所需的代码:

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile('http://example.com/');
$data = $dom->getElementById("banner");
echo $data->nodeValue."'n"

要转储整个 HTML 源代码,您可以调用:

echo $dom->saveHTML();
<?php
$f = curl_get_file_contents('http://example.com/')
$dom = new DOMDocument();
@$dom->loadHTML($f);
$data = $dom->getElementById("profile_section_container");
$html = $dom->saveHTML($data);
echo $html;
?>

如果您提供示例 html,这将有所帮助。

我不确定,但我记得有一次我想使用它,我无法将一些外部 URL 加载为文件,因为 php.ini directve allow-url-fopen 被设置为关闭......

因此,请检查您的 pnp.ini或尝试使用 fopen 打开 url,看看是否可以将 url 作为文件读取

<?php
$f = file_get_contents(url);
var_dump($f); // just to see the content
?>

问候;

米米兹

试试这个:

$dom= new DOMDocument();
$dom->loadHTMLFile('http://example.com/');
$data = $dom->getElementById("profile_section_container")->item(0);
$html = $data->saveHTML();
echo $html;

我认为现在您可以使用DOMDocument::loadHTML 也许您应该尝试 Doctype 存在(带有正则表达式),然后在必要时添加它,以确保让它声明...... 问候

米兹