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

标签 php html

我想在 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);

关于php - 如何在 PHP 中获取网页的 HTML 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/819182/

相关文章:

javascript - 使用php mysql进行编辑删除的Ajax多图像上传-需要调整大小

javascript - AJAX 请求返回 JS 而不是 HTML

javascript - iPhone布局中的背景颜色没有改变

java - 使用 <a> 标签在 jsp 页面中链接 php 页面

php - 使用 codeigniter 在 URL 中传递多个变量

php - 选择表中具有同一表中不同列的值的条件的行

php - 像数据库查询一样过滤掉数组

html - 如何更改 CSS 应用顺序

html - 重力不育系 |物化CSS |我们如何将 Materialize CSS 与 Grav 表单插件一起使用?

php - 在 php 代码中首先发送 "SetCookie"的问题