使用PHP函数之file_get_contents()读取远程URL内容的方法
file_get_contents()函数是 PHP 中用于读取文件的函数之一。除了可以读取本地文件之外,该函数还可以读取远程 URL 内容。在本文中,将介绍使用 PHP 函数 file_get_contents() 读取远程 URL 内容的方法。
file_get_contents() 函数的语法如下:
string file_get_contents(string $filename, bool $use_include_path = false, resource $context = null, int $offset = 0, int $length = null):string|false
其中,$filename 为要读取的文件名,可以是本地文件路径或远程 URL,$use_include_path 表示是否使用 include_path 查找文件,默认为 false;$context 表示用于 HTTP 命令的文本流上下文,如果未指定则使用默认上下文;$offset 表示读取的起始位置,默认为 0;$length 表示要读取的字节数,默认为 null(即读取整个文件)。
要读取远程 URL 内容,只需将 $filename 参数设置为要读取的 URL 地址即可。例如,要读取百度首页的内容,可以使用以下代码:
$content = file_get_contents('https://www.baidu.com');
echo $content;
运行上述代码,将在浏览器输出百度首页的 HTML 内容。
如果要发送 POST 请求或设置 HTTP 请求头等信息,可以通过 $context 参数传递上下文选项。例如,以下代码可以模拟浏览器发送 HTTP 请求:
$options = array(
'http' => array(
'method' => 'GET',
'header' => "Accept-language: en\r
" .
"Cookie: foo=bar\r
" .
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
),
);
$context = stream_context_create($options);
$content = file_get_contents('https://www.baidu.com', false, $context);
echo $content;
以上代码使用 $options 数组设置 HTTP 请求头和 Cookie 信息,并将其通过 stream_context_create() 函数创建为上下文选项。然后,将该上下文选项作为第三个参数传递给 file_get_contents() 函数,即可发送带有 HTTP 请求头和 Cookie 信息的 HTTP 请求,获取远程 URL 内容。
需要注意的是,如果针对某些 URL 地址出现了如下错误:
Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
这是由于 PHP 默认对 SSL 证书进行验证,如果远程服务器的证书无法通过验证则会出现上述错误。为了解决该问题,可以通过以下方法关闭 SSL 验证:
$options = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
$context = stream_context_create($options);
$content = file_get_contents('https://www.baidu.com', false, $context);
echo $content;
利用上述方法,可以轻松地使用 PHP 函数 file_get_contents() 读取远程 URL 内容。
