上一篇
本文目录导读:
🎯 PHP API集成与数据抓取全攻略(2025最新版)
📅 更新时间:2025年8月 | 🛠️ 技术栈:PHP 8.3 + cURL/Guzzle + RESTful API
https://api.example.com/v1/data
){"key": "value"}
)Authorization: Bearer xxx
)<?php // 初始化cURL $ch = curl_init(); // 设置URL与参数(GET请求) curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data?city=Beijing"); // 启用POST请求(若需要) // curl_setopt($ch, CURLOPT_POST, true); // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['param1'=>'val1'])); // 返回响应而非直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 添加认证Header curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer YOUR_ACCESS_TOKEN', 'Content-Type: application/json' ]); // 执行请求 $response = curl_exec($ch); // 错误处理 if(curl_errno($ch)) { die('Curl Error: ' . curl_error($ch)); } curl_close($ch); // 解析JSON响应 $data = json_decode($response, true); print_r($data); ?>
// 通过Composer安装:composer require guzzlehttp/guzzle require 'vendor/autoload.php'; $client = new GuzzleHttp\Client(); $response = $client->request('GET', 'https://api.example.com/data', [ 'query' => ['city' => 'Beijing'], 'headers' => [ 'Authorization' => 'Bearer YOUR_ACCESS_TOKEN', 'Accept' => 'application/json' ] ]); // 处理响应 if ($response->getStatusCode() === 200) { $data = json_decode($response->getBody(), true); echo "天气:".$data['temperature']."℃"; } else { echo "请求失败,状态码:".$response->getStatusCode(); }
方法 | 适用场景 | 示例代码片段 |
---|---|---|
file_get_contents |
简单GET请求 | $html = file_get_contents('https://example.com'); |
fopen +循环读取 |
大文件分块下载 | 见下文代码块 |
fsockopen |
底层Socket通信(需处理Header) | 自定义HTTP请求解析 |
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...');
curl_setopt($ch, CURLOPT_PROXY, 'http://123.45.67.89:8080');
usleep(rand(100000, 500000)); // 随机延迟0.1~0.5秒
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
防止中间人攻击 filter_var($input, FILTER_SANITIZE_STRING)
) curl_setopt($ch, CURLOPT_TIMEOUT, 10);
避免长时间阻塞📌 参考资料:
有任何具体API场景(如第三方支付/社交媒体API)需要深入讲解?👇 留言告诉我!
本文由 业务大全 于2025-08-15发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://up.7tqx.com/wenda/622494.html
发表评论