使用 file_get_contents 或 cURL 构造请求,设置 Content-Type: application/json 头,并将 JSON 字符串作为 body 发送。

file_get_contents 实现方式
通过 stream_context_create 创建上下文,配置 HTTP 方法、头部和主体数据,直接调用 file_get_contents 发起 POST 请求。

file_get_contents 是 PHP 内置的轻量级方案。核心在于构建正确的上下文数组。需要指定 method 为 POST,在 header 中声明 Content-Type 为 application/json,并将 json_encode 后的字符串赋值给 content。这种方式代码简洁,适合简单的脚本场景,但需注意服务器是否允许远程流操作。
cURL 完整程序示例
将以下代码保存为 post_json.php,在终端运行 php post_json.php 即可看到输出结果。

<?php
function postJson($url, $data) {
$ch = curl_init();
// 设置 URL 和其他选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($data))
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// 执行请求并获取响应
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo "HTTP Status: {$httpCode}\n";
echo "Response: {$response}\n";
}
curl_close($ch);
}
// 测试数据
$url = 'https://httpbin.org/post';
$data = [
'name' => 'developer',
'role' => 'backend',
'skills' => ['PHP', 'Go']
];
postJson($url, $data);
程序输出 HTTP 状态码 200 及接收到的 JSON 数据。若修改 $data 包含中文,需确认服务端支持 UTF-8。若 Content-Type 缺失,服务端可能拒绝解析。
cURL 提供了更精细的控制,是生产环境的首选。下面演示如何封装一个通用的 JSON POST 函数,处理 URL、数据和超时。
JSON 编码与特殊字符处理
确保 json_encode 正确处理中文及特殊符号,避免服务端解析失败。
在使用 json_encode 时,默认可能不转义中文,导致部分网关拦截。建议添加 JSON_UNESCAPED_UNICODE 标志。同时,检查返回状态码是否为 200,若出现 415 错误,通常是头部未正确设置;若出现 400 错误,往往是 JSON 格式非法。务必验证输入数据的结构是否符合目标 API 要求。