PHP 网站 API 使用完全指南
·
PHP 网站 API 使用完全指南
API 是现代 Web 开发的核心组成部分,PHP 可以通过多种方式使用 API。以下是完整的 PHP API 使用指南:
一、API 基础概念
API (Application Programming Interface) 允许不同系统之间进行通信。在 PHP 网站中,API 主要用于:
- 调用第三方服务(支付、地图、天气等)
- 为前端提供数据接口
- 实现微服务架构
二、PHP 调用 API 的方法
1. 使用 cURL(最常用)
php
<?php
// 初始化 cURL
$ch = curl_init();
// 设置 API 端点
$apiUrl = " ";
// 配置 cURL 选项
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer YOUR_ACCESS_TOKEN' // 如果需要认证
]
]);
// 执行请求
$response = curl_exec($ch);
// 错误处理
if (curl_errno($ch)) {
throw new Exception('cURL 错误: ' . curl_error($ch));
}
// 获取 HTTP 状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭连接
curl_close($ch);
// 处理响应
if ($httpCode === 200) {
$data = json_decode($response, true);
print_r($data);
} else {
throw new Exception("API 请求失败,状态码: $httpCode");
}
?>
2. 使用 file_get_contents(简单 GET 请求)
php
<?php
$apiUrl = "https://api.example.com/data?param=value";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "Authorization: Bearer YOUR_ACCESS_TOKEN\r\n"
]
]);
$response = file_get_contents($apiUrl, false, $context);
if ($response === false) {
throw new Exception("API 请求失败");
}
$data = json_decode($response, true);
print_r($data);
?>
3. 使用 Guzzle HTTP 客户端(推荐)
首先安装 Guzzle:
bash
composer require guzzlehttp/guzzle
然后使用:
php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://api.example.com',
'timeout' => 30,
]);
try {
// GET 请求
$response = $client->get('/users', [
'headers' => [
'Authorization' => 'Bearer YOUR_ACCESS_TOKEN',
'Accept' => 'application/json'
],
'query' => ['page' => 1]
]);
// POST 请求
// $response = $client->post('/users', [
// 'json' => ['name'更多推荐
所有评论(0)