<?php
function postJson(string $url, array $data, int $timeout = 10): ?array {
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('JSON 編碼失敗: ' . json_last_error_msg());
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $json,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_CONNECTTIMEOUT => min(5, $timeout),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
'Accept: application/json',
],
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'MyApp/1.0 (+https://example.com)',
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno) {
error_log("cURL [$errno] $error URL: $url");
return null;
}
if ($httpCode < 200 || $httpCode >= 300) {
error_log("HTTP $httpCode Response: $response");
return null;
}
return json_decode($response, true);
}
// 使用示例
$result = postJson('https://api.example.com/users', [
'name' => 'Hagrid',
'age' => 36,
'tags' => ['php', 'curl', 'json'],
]);
var_dump($result);
JSON_UNESCAPED_UNICODE 保留中文可讀,JSON_UNESCAPED_SLASHES 不轉義斜槿。curl_errno、HTTP 狀態碼、JSON 解碼錯誤,三層防護。CONNECTTIMEOUT(建立連接)與 TIMEOUT(整個請求)分開設置。極少數 API 需同時上傳文件與 JSON 元數據,需構造 multipart/related 或分兩步上傳。常規 JSON API **不支持**文件上傳,文件應單獨端點上傳返回 ID,再在 JSON 中引用 ID。
// Guzzle 7+
use GuzzleHttp\Client;
$client = new Client(['timeout' => 10]);
$response = $client->post('https://api.example.com/users', [
'json' => ['name' => 'Hagrid', 'age' => 36], // 自動設置 Header、編碼
]);
$data = $response->toArray();
優勢:自動處理 Header/編碼/重試/異步/中間件/測試雙,生產項目**強烈推薦**。
| 現象 | 原因 | 解決 |
|---|---|---|
| 服務端收到空 Body | 未設置 CURLOPT_POSTFIELDS 或用了 CURLOPT_POST 但字段為空 | 確保 CURLOPT_POSTFIELDS => $json |
| 415 Unsupported Media Type | 缺少 Content-Type: application/json | 加入 HTTPHEADER |
| 中文亂碼 | json_encode 未加 JSON_UNESCAPED_UNICODE 或服務端非 UTF-8 | 加選項、確認服務端編碼 |
| 大數據超時 | 默認 0 無超時,或超時太短 | 設置合理 TIMEOUT、考慮流式上傳 |