如何在PHP中获取网页的HTML代码?

2022-08-30 07:27:54

我想在PHP中检索链接(网页)的HTML代码。例如,如果链接是

https://stackoverflow.com/questions/ask

然后我想要所服务页面的HTML代码。我想检索此HTML代码并将其存储在PHP变量中。

我该怎么做?


答案 1

如果你的PHP服务器允许url fopen包装器,那么最简单的方法是:

$html = file_get_contents('https://stackoverflow.com/questions/ask');

如果你需要更多的控制,那么你应该看看cURL函数:

$c = curl_init('https://stackoverflow.com/questions/ask');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)

$html = curl_exec($c);

if (curl_error($c))
    die(curl_error($c));

// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);

答案 2

另外,如果你想以某种方式操纵检索到的页面,你可能想尝试一些php DOM解析器。我发现PHP Simple HTML DOM Parser非常容易使用。


推荐