以下是一个使用PHP开发API接口的示例:
<?php
// 设置响应头
header("Content-Type: application/json");
// 获取请求方法和路径
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['PATH_INFO'];
// 处理GET请求
if ($method === 'GET') {
if ($path === '/api/users') {
// 返回用户列表
$users = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane']
];
echo json_encode($users);
} else {
// 返回404错误
http_response_code(404);
echo json_encode(['error' => 'Not found']);
}
}
// 处理POST请求
if ($method === 'POST') {
if ($path === '/api/users') {
// 创建新用户
$data = json_decode(file_get_contents('php://input'), true);
// 处理请求数据并创建新用户
// ...
// 返回新用户的信息
$user = ['id' => 3, 'name' => 'Bob'];
echo json_encode($user);
} else {
// 返回404错误
http_response_code(404);
echo json_encode(['error' => 'Not found']);
}
}
?>
RewriteEngine On
RewriteRule ^(.*)$ api.php [QSA,L]
<?php
// 发送GET请求
$response = file_get_contents('http://example.com/api/users');
$users = json_decode($response, true);
foreach ($users as $user) {
echo $user['name'];
}
// 发送POST请求
$data = ['name' => 'Alice'];
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents('http://example.com/api/users', false, $context);
$user = json_decode($response, true);
echo $user['name'];
?>
以上示例演示了如何使用PHP开发API接口,并通过GET和POST请求与API进行通信。你可以根据自己的需求,修改和扩展这个示例来实现更复杂的功能。
上一篇:php批量修改文件内容
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站