下面是一份不依赖框架的 PHP JSON API 示例,复制为 api.php 后即可运行。适合做小型接口、后台工具接口或快速原型。
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
function json_response(int $code, string $message, $data = null, int $httpStatus = 200): void
{
http_response_code($httpStatus);
echo json_encode([
'code' => $code,
'message' => $message,
'data' => $data,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
function json_input(): array
{
$raw = file_get_contents('php://input');
if ($raw === '' || $raw === false) {
return [];
}
$data = json_decode($raw, true);
if (!is_array($data)) {
json_response(400, '请求 JSON 格式错误', null, 400);
}
return $data;
}
function require_field(array $data, string $field): string
{
$value = trim((string)($data[$field] ?? ''));
if ($value === '') {
json_response(422, "字段 {$field} 不能为空", null, 422);
}
return $value;
}
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
if ($method === 'GET' && $path === '/api/health') {
json_response(0, 'ok', [
'service' => 'php-json-api',
'time' => date('Y-m-d H:i:s'),
]);
}
if ($method === 'POST' && $path === '/api/messages') {
$input = json_input();
$title = require_field($input, 'title');
$content = require_field($input, 'content');
json_response(0, '创建成功', [
'id' => time(),
'title' => $title,
'content' => $content,
], 201);
}
json_response(404, '接口不存在', null, 404); 运行方式:
# 启动本地服务
php -S 127.0.0.1:8000 api.php
# 健康检查
curl http://127.0.0.1:8000/api/health
# 创建消息
curl -X POST http://127.0.0.1:8000/api/messages -H 'Content-Type: application/json' -d '{"title":"Hello","content":"PHP API"}'