我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
当前回答
将域对象格式化为JSON的一种简单方法是使用Marshal Serializer。 然后将数据传递给json_encode,并根据需要发送正确的Content-Type报头。 如果您正在使用Symfony这样的框架,则不需要手动设置标头。在那里您可以使用JsonResponse。
例如,处理Javascript的正确内容类型应该是application/ Javascript。
或者如果你需要支持一些相当老的浏览器,最安全的是文本/javascript。
对于所有其他用途,如移动应用程序,使用application/json作为内容类型。
这里有一个小例子:
<?php
...
$userCollection = [$user1, $user2, $user3];
$data = Marshal::serializeCollectionCallable(function (User $user) {
return [
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'birthday' => $user->getBirthday()->format('Y-m-d'),
'followers => count($user->getFollowers()),
];
}, $userCollection);
header('Content-Type: application/json');
echo json_encode($data);
其他回答
如上所述:
header('Content-Type: application/json');
会完成这项工作。但请记住:
即使没有使用这个报头,Ajax读取json也没有问题,除非您的json包含一些HTML标记。在这种情况下,您需要将头文件设置为application/json。 确保您的文件不是用UTF8-BOM编码的。这种格式在文件顶部添加了一个字符,因此header()调用将失败。
尝试json_encode对数据进行编码,并设置带有header的content-type (' content-type: application/json');
返回JSON的完整的PHP代码如下:
$option = $_GET['option'];
if ( $option == 1 ) {
$data = [ 'a', 'b', 'c' ];
// will encode to JSON array: ["a","b","c"]
// accessed as example in JavaScript like: result[1] (returns "b")
} else {
$data = [ 'name' => 'God', 'age' => -1 ];
// will encode to JSON object: {"name":"God","age":-1}
// accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}
header('Content-type: application/json');
echo json_encode( $data );
根据json_encode的手册,该方法可以返回一个非字符串(false):
成功时返回JSON编码字符串,失败时返回FALSE。
当这种情况发生时,echo json_encode($data)将输出空字符串,这是无效的JSON。
如果json_encode的参数包含一个非UTF-8字符串,则json_encode将失败(并返回false)。
这个错误情况应该在PHP中捕获,例如:
<?php
header("Content-Type: application/json");
// Collect what you need in the $data variable.
$json = json_encode($data);
if ($json === false) {
// Avoid echo of empty string (which is invalid JSON), and
// JSONify the error message instead:
$json = json_encode(["jsonError" => json_last_error_msg()]);
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError":"unknown"}';
}
// Set HTTP response status code to: 500 - Internal Server Error
http_response_code(500);
}
echo $json;
?>
然后,接收端当然应该知道jsonError属性的存在表明了一个错误条件,它应该相应地处理这个错误条件。
在生产模式下,最好只向客户端发送一般的错误状态,并记录更具体的错误消息,以便以后进行调查。
在PHP文档中阅读更多关于处理JSON错误的内容。
如果你在WordPress中这样做,那么有一个简单的解决方案:
add_action( 'parse_request', function ($wp) {
$data = /* Your data to serialise. */
wp_send_json_success($data); /* Returns the data with a success flag. */
exit(); /* Prevents more response from the server. */
})
请注意,这不在wp_head钩子中,该钩子将始终返回大部分头部,即使您立即退出。parse_request在序列中出现得更早。