file_get_contents()
是 PHP 中一个常用的函数,用于将整个文件读入一个字符串。当用于获取远程 URL 内容时,它实际上是一个简单的 HTTP 客户端。
原因:目标 URL 可能进行了 301/302 重定向,而 file_get_contents()
默认不跟随重定向。
解决方案:
$context = stream_context_create([
'http' => [
'follow_location' => true // 启用跟随重定向
]
]);
$content = file_get_contents($url, false, $context);
原因:服务器可能根据 User-Agent 返回不同内容。
解决方案:
$context = stream_context_create([
'http' => [
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\r\n"
]
]);
$content = file_get_contents($url, false, $context);
原因:SSL 证书验证失败可能导致获取内容失败或不同。
解决方案:
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
]);
$content = file_get_contents($url, false, $context);
原因:浏览器可能携带了 Cookie 或保持会话状态。
解决方案:
$context = stream_context_create([
'http' => [
'header' => "Cookie: name=value\r\n"
]
]);
$content = file_get_contents($url, false, $context);
原因:现代网站大量使用 JavaScript 动态加载内容。
解决方案:考虑使用专门的 HTTP 客户端库如 Guzzle,或浏览器自动化工具如 Puppeteer。
原因:返回内容可能使用了不同的字符编码。
解决方案:
$content = file_get_contents($url);
$content = mb_convert_encoding($content, 'UTF-8', 'auto');
原因:服务器可能根据 IP、Referer 或其他头部信息返回不同内容。
解决方案:模拟完整的 HTTP 请求头部:
$context = stream_context_create([
'http' => [
'header' => "User-Agent: Mozilla/5.0\r\n" .
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
"Accept-Language: en-US,en;q=0.5\r\n" .
"Accept-Encoding: gzip, deflate\r\n" .
"Connection: keep-alive\r\n" .
"Referer: https://example.com/\r\n"
]
]);
$content = file_get_contents($url, false, $context);
对于复杂的 HTTP 请求,建议使用专门的 HTTP 客户端库如 Guzzle:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->get($url, [
'headers' => [
'User-Agent' => 'Mozilla/5.0',
],
'allow_redirects' => true
]);
$content = (string)$response->getBody();
get_headers()
检查响应头$http_response_header
变量获取响应信息通过以上方法,您应该能够解决 file_get_contents()
返回内容与浏览器不一致的问题。