JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。在PHP中,JSON常用于前后端数据交互。
原因:PHP数组或对象未正确编码为JSON,或接收端未正确解码。
解决方案:
// 正确编码为JSON
$data = ['name' => 'John', 'age' => 30];
$json = json_encode($data);
// 设置正确的Content-Type头
header('Content-Type: application/json');
echo $json;
原因:未设置正确的Content-Type头或已有输出导致头部无法修改。
解决方案:
// 确保在输出任何内容前设置头部
ob_start(); // 开启输出缓冲
header('Content-Type: application/json');
echo json_encode($data);
ob_end_flush(); // 发送输出并关闭缓冲
原因:前端从不同域访问PHP JSON API时被浏览器阻止。
解决方案:
header('Access-Control-Allow-Origin: *'); // 允许所有域
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');
原因:JSON字符串格式不正确,包含非法字符或编码问题。
解决方案:
// 检查JSON编码是否成功
$json = json_encode($data);
if ($json === false) {
die('JSON编码错误: ' . json_last_error_msg());
}
// 处理特殊字符
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
原因:PHP错误或警告信息被输出,破坏了JSON格式。
解决方案:
// 关闭错误显示
ini_set('display_errors', 0);
error_reporting(0);
// 或者在开发环境中记录到日志
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/php-error.log');
<?php
// 开启输出缓冲
ob_start();
// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
// 准备数据
$data = [
'status' => 'success',
'message' => 'Data retrieved successfully',
'data' => [
['id' => 1, 'name' => 'Item 1'],
['id' => 2, 'name' => 'Item 2']
]
];
// 编码为JSON
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// 检查编码是否成功
if ($json === false) {
$errorData = [
'status' => 'error',
'message' => 'JSON encoding failed',
'error' => json_last_error_msg()
];
echo json_encode($errorData);
} else {
echo $json;
}
// 发送输出
ob_end_flush();
?>
application/json
json_last_error()
和json_last_error_msg()
获取JSON处理错误信息