Z
ZHANK
编程在线教程PHP 教程JSON 与 API 开发
进阶技巧

JSON 与 API 开发

json_encode/decode、header 设置响应头、REST API 开发

JSON 与 API 开发

PHP 处理 JSON 极其简单——json_encodejson_decode 是仅需的两个函数。配合 header() 设置响应头,就能构建 REST API。

学完本章你将: 掌握 json_encode/decode、header 响应头、REST API 开发。


编码与解码

php
<?php
$data = [
    "name" => "小明",
    "age" => 25,
    "hobbies" => ["编程", "跑步"],
];

// 编码:数组/对象 → JSON
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $json;
// {
//     "name": "小明",
//     "age": 25,
//     "hobbies": ["编程", "跑步"]
// }

// 解码:JSON → 数组/对象
$arr = json_decode($json, true);       // 返回关联数组
$obj = json_decode($json);             // 返回 stdClass 对象
echo $obj->name;                       // "小明"

构建 REST API

php
<?php
// api/users.php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");

$method = $_SERVER["REQUEST_METHOD"];

try {
    match ($method) {
        "GET" => getUsers(),
        "POST" => createUser(),
        "PUT" => updateUser(),
        "DELETE" => deleteUser(),
        default => throw new Exception("不支持的请求方法"),
    };
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(["error" => $e->getMessage()]);
}

function getUsers(): void {
    $users = [["id" => 1, "name" => "小明"]];
    echo json_encode(["data" => $users]);
}

function createUser(): void {
    $input = json_decode(file_get_contents("php://input"), true);
    // 验证 + 保存...
    http_response_code(201);
    echo json_encode(["message" => "创建成功"]);
}