从PHP脚本返回JSON

我想从PHP脚本返回JSON。

我只是回显结果吗?我必须设置Content-Type标头吗?

1424549 次浏览

将内容类型设置为header('Content-type: application/json');,然后回显您的数据。

你问题的答案在这里

它说。

JSON文本的MIME媒体类型是应用程序/json。

因此,如果您将标头设置为该类型,并输出JSON字符串,它应该可以工作。

是的,您需要使用回显来显示输出。Mimetype:应用程序/json

尝试json_encode对数据进行编码并使用header('Content-type: application/json');设置内容类型。

虽然没有它通常很好,但您可以并且应该设置Content-Type标头:

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

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

一个完整而清晰的PHP代码返回JSON是:

$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 );

您可以使用这个小PHP库。它会发送标头并为您提供一个易于使用的对象。

它看起来像:

<?php// Include the json classinclude('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,您可以在打印任何其他内容之前添加此header('Content-Type: application/json');,这样您就可以打印您的客户端echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

根据手动#0,该方法可以返回一个非字符串(虚假):

成功时返回JSON编码字符串,失败时返回FALSE

发生这种情况时,echo json_encode($data)将输出空字符串,即JSON请求不正确

例如,如果其参数包含非UTF-8字符串,json_encode将失败(并返回false)。

这个错误条件应该在PHP中捕获,例如这样:

<?phpheader("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 Errorhttp_response_code(500);}echo $json;?>

那么接收端当然应该知道错误信息属性的存在表示错误条件,它应该相应地处理它。

在生产模式下,最好只向客户端发送通用错误状态并记录更具体的错误消息以供以后调查。

阅读更多关于处理PHP的文档中的JSON错误的信息。

如上所述:

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

将使工作。但请记住:

  • 即使不使用此标头,Ajax读取json也没有问题,除非您的json包含一些超文本标记语言标签。在这种情况下,您需要将标头设置为Application/json。

  • 确保您的文件未以UTF8-BOM编码。这种格式在文件顶部添加一个字符,因此您的head()调用将失败。

设置访问安全性也很好-只需将*替换为您希望能够访问它的域。

<?phpheader('Access-Control-Allow-Origin: *');header('Content-type: application/json');$response = array();$response[0] = array('id' => '1','value1'=> 'value1','value2'=> 'value2');
echo json_encode($response);?>

以下是更多示例:如何绕过Access Control Allow-Origin?

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

希望这个帮助谢谢

<?phpheader("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格式的结果集,可以这样做:

<?php
$db = mysqli_connect("localhost","root","","mylogs");//MSG$query = "SELECT * FROM logs LIMIT 20";$result = mysqli_query($db, $query);//Add all records to an array$rows = array();while($row = $result->fetch_array()){$rows[] = $row;}//Return result to jTable$qryResult = array();$qryResult['logs'] = $rows;echo json_encode($qryResult);
mysqli_close($db);
?>

有关使用jQuery解析结果的帮助,请查看本教程

将域对象格式化为JSON的一种简单方法是使用元帅序列化器。然后将数据传递给json_encode并根据您的需要发送正确的Content-Type标头。如果您使用的是Symfony之类的框架,则无需手动设置标头。在那里您可以使用jsonResponse

例如,处理Javascript的正确Content-Type是application/javascript

或者,如果您需要支持一些非常旧的浏览器,最安全的是text/javascript

对于移动应用程序等所有其他目的,请使用application/json作为Content-Type。

下面是一个小例子:

<?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);
<?php$data = /** whatever you're serializing **/;header("Content-type: application/json; charset=utf-8");echo json_encode($data);?>

一个简单的函数返回JSON响应HTTP状态码

function json_response($data=null, $httpStatus=200){header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();}

每当您尝试为API返回JSON响应时,请确保您有适当的标头,并确保您返回有效的JSON数据。

这是一个示例脚本,可帮助您从PHP数组返回JSON响应或从JSON文件。

PHP脚本(代码):

<?php
// Set required headersheader('Content-Type: application/json; charset=utf-8');header('Access-Control-Allow-Origin: *');
/*** Example: First** Get JSON data from JSON file and retun as JSON response*/
// Get JSON data from JSON file$json = file_get_contents('response.json');
// Output, responseecho $json;
/** =. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.  */
/*** Example: Second** Build JSON data from PHP array and retun as JSON response*/
// Or build JSON data from array (PHP)$json_var = ['hashtag' => 'HealthMatters','id' => '072b3d65-9168-49fd-a1c1-a4700fc017e0','sentiment' => ['negative' => 44,'positive' => 56,],'total' => '3400','users' => [['profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg','screen_name' => 'rayalrumbel','text' => 'Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.','timestamp' => '\{\{$timestamp}}',],['profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg','screen_name' => 'mikedingdong','text' => 'Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.','timestamp' => '\{\{$timestamp}}',],['profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg','screen_name' => 'ScottMili','text' => 'Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.','timestamp' => '\{\{$timestamp}}',],['profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg','screen_name' => 'yogibawa','text' => 'Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.','timestamp' => '\{\{$timestamp}}',],],];
// Output, responseecho json_encode($json_var);

JSON文件(JSON数据):

{"hashtag": "HealthMatters","id": "072b3d65-9168-49fd-a1c1-a4700fc017e0","sentiment": {"negative": 44,"positive": 56},"total": "3400","users": [{"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg","screen_name": "rayalrumbel","text": "Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.","timestamp": "\{\{$timestamp}}"},{"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg","screen_name": "mikedingdong","text": "Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.","timestamp": "\{\{$timestamp}}"},{"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg","screen_name": "ScottMili","text": "Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.","timestamp": "\{\{$timestamp}}"},{"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg","screen_name": "yogibawa","text": "Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.","timestamp": "\{\{$timestamp}}"}]}

JSON ScreesHot:

在此处输入图片描述

这个问题得到了很多答案,但没有一个涵盖返回干净JSON的整个过程,以及防止JSON响应格式错误所需的一切。

/** returnJsonHttpResponse* @param $success: Boolean* @param $data: Object or Array*/function returnJsonHttpResponse($success, $data){// remove any string that could create an invalid JSON// such as PHP Notice, Warning, logs...ob_clean();
// this will clean up any previously added headers, to start cleanheader_remove();
// Set the content type to JSON and charset// (charset can be set to something else)header("Content-type: application/json; charset=utf-8");
// Set your HTTP response code, 2xx = SUCCESS,// anything else will be error, refer to HTTP documentationif ($success) {http_response_code(200);} else {http_response_code(500);}    
// encode your PHP Object or Array into a JSON string.// stdClass or arrayecho json_encode($data);
// making sure nothing is addedexit();}

参考文献:

response_remove

ob_clean

内容类型的JSON

HTTP代码

http_response_code

json_encode

如果你在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在序列中出现得更早。

如果您想要js对象,请使用头内容类型:

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

如果您只想要json:删除头内容类型属性,只需编码和回声。

<?php$data = /** whatever you're serializing **/;echo json_encode($data);