使用原生PHP可创建RESTful API,通过定义数据源、解析请求方法与路径,实现GET、POST、PUT、DELETE操作,并返回JSON响应;可用cURL或fetch调用。1. 定义用户数据数组模拟数据库;2. 用$_SERVER['REQUEST_METHOD']获取请求类型,解析URL路径获取ID;3. 根据方法处理对应逻辑,如GET返回用户列表或单个用户,POST创建新用户并返回201状态;4. 设置Content-Type: application/json响应头;5. 调用API时,使用PHP cURL发送GET请求获取数据,或POST提交JSON数据;6. 建议重写URL、验证输入、统一错误格式,生产环境优先使用框架。

在PHP中创建和调用RESTful API是现代Web开发中的常见需求,尤其适用于前后端分离或为移动应用提供数据服务。下面介绍如何使用原生PHP构建一个简单的RESTful API,并说明如何调用它。
构建API的核心是根据HTTP请求方法(GET、POST、PUT、DELETE)来处理不同的操作。以下是基本步骤:
■ 定义数据源通常数据来自数据库,这里以数组模拟数据:
$users = [
1 => ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
2 => ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com']
];
使用$_SERVER['REQUEST_METHOD']判断请求类型,解析URL路径获取资源ID:
立即学习“PHP免费学习笔记(深入)”;
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = explode('/', $path);
$id = isset($parts[3]) ? (int)$parts[3] : null;
根据请求方法执行对应逻辑:
示例代码片段:
switch ($method) {
case 'GET':
if ($id) {
if (isset($users[$id])) {
echo json_encode($users[$id]);
} else {
http_response_code(404);
echo json_encode(['error' => 'User not found']);
}
} else {
echo json_encode(array_values($users));
}
break;
case 'POST':
$input = json_decode(file_get_contents('php://input'), true);
$new_id = max(array_keys($users)) + 1;
$users[$new_id] = [
'id' => $new_id,
'name' => $input['name'],
'email' => $input['email']
];
http_response_code(201);
echo json_encode($users[$new_id]);
break;
// 其他方法(PUT、DELETE)类似处理...
}
确保返回JSON格式:
header('Content-Type: application/json');
可以使用多种方式调用已创建的API,比如JavaScript的fetch、curl命令或PHP的cURL扩展。
■ 使用PHP cURL调用API例如从另一个脚本获取用户列表:
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://localhost/api/users"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); print_r($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/api/users");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'name' => 'Charlie',
'email' => 'charlie@example.com'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
基本上就这些。原生PHP实现简单API适合学习和小型项目,实际生产环境推荐使用成熟框架提高效率和稳定性。
以上就是php数据如何创建和调用RESTful API_php数据构建API接口的步骤的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号