PHP 使用 curl 请求 API 并获取结果
PHP 使用 curl 请求 API 并获取结果
本文介绍了使用 PHP 的 curl 函数库向 API 发起请求,并获取返回结果的方法。
代码示例:
$id = rand(1, 5000); // 生成 1-5000 的随机 ID
$hash = substr(md5('yg_book_' . $id), 5, 16); // 获取 hash 值
$url = 'http://localhost/home/api/updatecachemip?id=' . $id . '&hash=' . $hash; // 设置请求链接
$ch = curl_init(); // 初始化 curl
curl_setopt($ch, CURLOPT_URL, $url); // 设置请求链接
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置返回结果为字符串
$result = curl_exec($ch); // 执行 curl 请求
curl_close($ch); // 关闭 curl
echo $url . '<br>'; // 输出链接
echo $result; // 输出结果
代码解释:
- 生成随机 ID 和 hash 值,并将它们作为参数添加到请求 URL 中。
- 使用
curl_init()初始化 curl。 - 使用
curl_setopt()设置请求链接和返回结果类型。 - 使用
curl_exec()执行 curl 请求并获取结果。 - 使用
curl_close()关闭 curl 连接。 - 输出请求链接和返回结果。
注意:
- 此代码示例仅供参考,实际使用时需要根据具体的 API 接口文档进行调整。
- 需要确保服务器已安装 curl 扩展。
- 可以根据需要对返回结果进行解析和处理。
原文地址: https://www.cveoy.top/t/topic/mYbL 著作权归作者所有。请勿转载和采集!