我想从PHP脚本返回JSON。

我只是重复结果吗?我必须设置内容类型头吗?


当前回答

这是一个简单的PHP脚本,返回男性女性和用户id作为json值将是任何随机值,因为你调用脚本json. PHP。

希望能有所帮助,谢谢

<?php
header("Content-type: application/json");
$myObj=new \stdClass();
$myObj->user_id = rand(0, 10);
$myObj->male = rand(0, 5);
$myObj->female = rand(0, 5);
$myJSON = json_encode($myObj);
echo $myJSON;
?>

其他回答

根据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错误的内容。

虽然你通常没有它也没问题,但你可以也应该设置Content-Type头文件:

<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);

如果我没有使用特定的框架,我通常允许一些请求参数修改输出行为。通常对于快速故障排除,不发送报头或有时print_r数据有效负载来观察它(尽管在大多数情况下,这应该是不必要的)是很有用的。

您可以使用这个小型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();
?>

如果你需要从发送自定义信息的php中获取json,你可以添加这个头('Content-Type: application/json');在打印任何其他东西之前,所以然后你可以打印你的自定义echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

如上所述:

header('Content-Type: application/json');

会完成这项工作。但请记住:

即使没有使用这个报头,Ajax读取json也没有问题,除非您的json包含一些HTML标记。在这种情况下,您需要将头文件设置为application/json。 确保您的文件不是用UTF8-BOM编码的。这种格式在文件顶部添加了一个字符,因此header()调用将失败。