萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 网络数据抓取四大方法对比:file_get_contents、fopen、POST 上下文、cURL

方法对比表

方法适用场景优点缺点推荐指数
file_get_contents (GET)简单 GET 请求代码极简,内置流上下文支持 POST无超时控制(需流上下文)、无重定向控制、错误处理弱⭐⭐
fopen + fread流式读取大文件可逐行/分块处理,内存友好手动拼装 HTTP 协议繁琐,无自动重定向⭐⭐
file_get_contents (POST + stream_context)简单 POST 无依赖环境纯 PHP 实现 POST,无需 cURL 扩展配置繁琐,超时/证书/代理支持有限⭐⭐⭐
cURL生产级 HTTP 客户端功能最全:证书、代理、多请求并发、Cookie、限速、断点续传需安装扩展,API 相对繁琐⭐⭐⭐⭐⭐

代码示例

1. file_get_contents GET

$html = file_get_contents('https://api.example.com/data');

2. fopen 流式读取

$fp = fopen('https://api.example.com/large', 'r');
while (!feof($fp)) { echo fread($fp, 8192); }
fclose($fp);

3. file_get_contents POST

$data = http_build_query(array('foo'=>'bar', 'token'=>'xyz'));
$opts = array('http' => array(
    'method'  => 'POST',
    'header'  => 'Content-Type: application/x-www-form-urlencoded',
    'content' => $data,
    'timeout' => 30,
));
$ctx = stream_context_create($opts);
$result = file_get_contents('https://api.example.com/endpoint', false, $ctx);

4. cURL 标准范式

$ch = curl_init('https://api.example.com/endpoint');
curl_setopt_array($ch, array(
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $data,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => array('Content-Type: application/x-www-form-urlencoded'),
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_CAINFO         => '/etc/ssl/certs/ca-certificates.crt',
));
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

最佳实践建议

  • 新项目统一使用 Guzzle 或 Symfony HttpClient(PSR-18 标准),封装重试、熔断、日志、测试双工。
  • 仅做简单健康检查/爬虫可用 file_get_contents + 流上下文。
  • 必须用 cURL 场景:客户端证书双向认证、WebSocket、HTTP/2、并发多请求 (curl_multi)、SOCKS5 代理。
copyright © 萬盛學電腦網 all rights reserved