我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
我想从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在序列中出现得更早。
其他回答
如果你需要从发送自定义信息的php中获取json,你可以添加这个头('Content-Type: application/json');在打印任何其他东西之前,所以然后你可以打印你的自定义echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';
<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>
您可以使用这个小型PHP库。它发送头文件并给你一个容易使用它的对象。
它看起来是这样的:
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
是的,你需要使用echo来显示输出。Mimetype: application / 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);