PHPAPI响应格式与状态码规范统一的API响应格式让前后端协作更高效。规范的HTTP状态码让错误处理更清晰。今天说说PHP中API响应格式和状态码的使用。统一的JSON响应格式。phpclass ApiResponse{public static function success(mixed $data null, string $message success): string{return json_encode([code 0,message $message,data $data,], JSON_UNESCAPED_UNICODE);}public static function error(string $message, int $code -1, mixed $data null): string{return json_encode([code $code,message $message,data $data,], JSON_UNESCAPED_UNICODE);}public static function paginate(array $items, int $total, int $page, int $perPage): string{return json_encode([code 0,message success,data [items $items,total $total,page $page,per_page $perPage,total_pages ceil($total / $perPage),],], JSON_UNESCAPED_UNICODE);}public static function send(mixed $data, int $statusCode 200): void{http_response_code($statusCode);header(Content-Type: application/json; charsetutf-8);echo is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE);}}?HTTP状态码的正确使用。php// 2xx 成功200 OK,201 Created,204 No Content,// 3xx 重定向301 Moved Permanently,302 Found,304 Not Modified,// 4xx 客户端错误400 Bad Request,401 Unauthorized,403 Forbidden,404 Not Found,405 Method Not Allowed,409 Conflict,422 Unprocessable Entity,429 Too Many Requests,// 5xx 服务端错误500 Internal Server Error,502 Bad Gateway,503 Service Unavailable,?API错误处理。phpclass ApiException extends Exception{public function __construct(string $message,int $code 400,private ?array $details null) {parent::__construct($message, $code);}public function getDetails(): ?array{return $this-details;}public function toResponse(): array{$response [error true,message $this-getMessage(),code $this-getCode(),];if ($this-details) {$response[details] $this-details;}return $response;}}set_exception_handler(function (Throwable $e) {if ($e instanceof ApiException) {http_response_code($e-getCode());echo json_encode($e-toResponse(), JSON_UNESCAPED_UNICODE);} else {http_response_code(500);echo json_encode([error true,message $_SERVER[APP_ENV] development ? $e-getMessage() : 服务器内部错误,], JSON_UNESCAPED_UNICODE);error_log(API错误: {$e-getMessage()} in {$e-getFile()}:{$e-getLine()});}});?API版本信息。phpfunction addApiVersionHeaders(): void{header(X-API-Version: 2.0);header(X-API-Deprecated: true);header(X-API-Sunset-Date: 2024-12-31);}?分页信息的响应。phpfunction paginatedResponse(PDO $pdo, string $sql, int $page, int $perPage): string{$offset ($page - 1) * $perPage;$countSql SELECT COUNT(*) FROM ( . $sql . ) AS count;$total (int)$pdo-query($countSql)-fetchColumn();$stmt $pdo-prepare($sql LIMIT $perPage OFFSET $offset);$stmt-execute();$items $stmt-fetchAll();return ApiResponse::paginate($items, $total, $page, $perPage);}?统一的API响应格式让前端错误处理更简单。code字段区分业务错误message字段给出描述。HTTP状态码反映请求结果。分页信息包含总数和总页数。API版本信息帮助客户端升级。