如何在PHP中获取网页的HTML代码?
我想在PHP中检索链接(网页)的HTML代码。例如,如果链接是
https://stackoverflow.com/questions/ask
然后我想要所服务页面的HTML代码。我想检索此HTML代码并将其存储在PHP变量中。
我该怎么做?
我想在PHP中检索链接(网页)的HTML代码。例如,如果链接是
https://stackoverflow.com/questions/ask
然后我想要所服务页面的HTML代码。我想检索此HTML代码并将其存储在PHP变量中。
我该怎么做?
如果你的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);