在現代 Web 開發中,JSON(JavaScript Object Notation)已成為資料交換的標準格式。本文將深入淺出地介紹 PHP 中 JSON 的核心操作,包含編碼、解碼與實際 API 串接應用,幫助你快速掌握這項必備技能。
JSON 全稱 JavaScript Object Notation,是一種基於 JavaScript 語言子集的輕量級資料交換格式。雖然源自 JavaScript,但它完全獨立於程式語言,幾乎所有主流語言都內建支援。相比 XML,JSON 結構更簡潔、解析速度更快、頻寬佔用更低,是前後端分離架構與跨平台資料傳輸的首選。
| 函數 | 用途 | 回傳值 |
|---|---|---|
json_encode() | 將 PHP 陣列/物件轉為 JSON 字串 | JSON 字串或 false(失敗) |
json_decode() | 將 JSON 字串解析為 PHP 變數 | 物件(預設)或關聯陣列(第 2 參數為 true) |
json_last_error() | 取得最後一次操作的錯誤代碼 | 整數錯誤代碼 |
json_last_error_msg() | 取得人類可讀的錯誤訊息 | 字串 |
<?php
$fruits = ['蘋果', '香蕉', '橘子', '葡萄'];
$json = json_encode($fruits, JSON_UNESCAPED_UNICODE); // 保留中文不轉義
echo $json; // ["蘋果","香蕉","橘子","葡萄"]
關鍵選項說明:
JSON_UNESCAPED_UNICODE:不將 Unicode 字元轉為 \uXXXX 格式,保持中文可讀。JSON_PRETTY_PRINT:輸出縮排格式,方便除錯。JSON_FORCE_OBJECT:強制輸出為物件格式(即使是索引陣列)。<?php
$user = [
'id' => 1001,
'name' => '王小明',
'email' => 'xiaoming@example.com',
'roles' => ['admin', 'editor'],
'active' => true
];
echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
輸出結果:
{
"id": 1001,
"name": "王小明",
"email": "xiaoming@example.com",
"roles": ["admin", "editor"],
"active": true
}
<?php
$jsonStr = '{"product":"筆電","price":32000,"tags":["熱銷","新品"],"spec":{"cpu":"i7","ram":"16GB"}}';
// 解碼為物件(預設)
$obj = json_decode($jsonStr);
echo $obj->product; // 筆電
echo $obj->spec->cpu; // i7
// 解碼為關聯陣列(第 2 參數 true)
$arr = json_decode($jsonStr, true);
echo $arr['price']; // 32000
echo $arr['tags'][0]; // 熱銷
<?php
function safeJsonDecode(string $json, bool $assoc = false) {
$result = json_decode($json, $assoc);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('JSON 解析失敗:' . json_last_error_msg());
}
return $result;
}
try {
$data = safeJsonDecode($apiResponse);
} catch (RuntimeException $e) {
error_log($e->getMessage());
// 回應錯誤或使用預設值
}
<?php
function fetchWeather(string $city): ?array {
$url = "https://api.openweathermap.org/data/2.5/weather?q={$city}&appid=YOUR_KEY&units=metric&lang=zh_tw";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) return null;
$data = json_decode($response, true);
return [
'city' => $data['name'],
'temp' => $data['main']['temp'],
'desc' => $data['weather'][0]['description'],
'humidity' => $data['main']['humidity'],
];
}
// 使用範例
$weather = fetchWeather('Taipei');
if ($weather) {
echo "{$weather['city']} 目前 {$weather['temp']}°C,{$weather['desc']}";
}
JSON_UNESCAPED_UNICODE 旗標。json_decode 預設將大整數轉為 float,使用 JSON_BIGINT_AS_STRING 保持字串格式。JsonSerializable 介面自訂輸出。Content-Encoding: gzip)。json_encode,改為批次處理。igbinary + msgpack 等二進位序列化替代方案。掌握 JSON 操作是 PHP 開發者的基本功,善用內建函數與錯誤處理,能讓你的 API 串接更穩健、資料交換更高效。下次面對第三方 API 或前後端協作時,就能游刃有餘了!