从PHP脚本中返回JSON

我想从一个PHP脚本中返回JSON。

我可以直接回显结果吗?我必须设置 "Content-Type "头吗?

解决办法

虽然你通常不需要它,但你可以而且应该设置Content-Type头。

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

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

评论(10)

一段完整的漂亮而清晰的返回JSON的PHP代码是:{{{7774088}}。

$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 );
评论(1)

根据json_encode手册,该方法可以返回一个非字符串(false)。

&gt.方法可以返回一个非字符串(false): 成功时返回一个JSON编码的字符串,失败时返回FALSE

当这种情况发生时,echo json_encode($data)将输出空字符串,即无效JSON

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

这个错误条件应该在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(array("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's Documentation中阅读更多关于处理JSON错误的信息。

评论(2)

尝试用[json_encode][1]对数据进行编码,并用header(&#39;Content-type.Application/json&#39;);设置内容类型。 application/json');`。

[1]: http://php.net/manual/en/function.json-encode.php

评论(0)

header('Content-type: application/json');设置内容类型,然后呼出你的数据。

评论(0)

设置访问安全也是很好的--只需将*替换为你希望能够访问的域名即可。

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

echo json_encode($response); 
?>

这里有更多关于这方面的样本。 https://stackoverflow.com/questions/7564832/how-to-bypass-access-control-allow-origin

评论(0)

如上所述。

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

将使工作。 但请记住,即使不使用这个头,.Ajax也能顺利读取json。

  • 即使不使用这个头,Ajax读取json也没有问题,除非你的json包含一些HTML标签。 在这种情况下,你需要将头设置为application/json。

  • 确保你的文件没有使用UTF8-BOM编码。 这种格式会在文件顶部增加一个字符,所以你的header()调用会失败。

评论(0)
<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>
评论(0)

你的问题的答案在这里

它说。

JSON文本的MIME媒体类型是 application/json。

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

评论(0)

是的,你需要使用echo来显示输出。Mimetype: application/json

评论(0)

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

评论(0)

这是一个简单的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;
?>
评论(1)

如果你查询数据库并需要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解析结果的帮助,请看本教程

评论(0)

将域对象格式化为JSON的一个简单方法是使用Marshal Serializer.然后将数据传递给json_encode,并根据你的需要发送正确的Content-Type头。 然后将数据传递给json_encode,并根据你的需求发送正确的Content-Type头。 如果你使用的是像Symfony这样的框架,你就不需要手动设置头文件了,你可以在那里使用[Json_encode]()。 在那里你可以使用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);
评论(0)

你可以使用这个【PHP小库】[1]。 它发送头文件,并给你一个对象,让你轻松使用它。

它看起来像:

<?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();
?>

[1]: https://github.com/AlexisTM/Simple-Json-PHP

评论(0)

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

函数 json_response($data=null, $httpStatus=200)
{
header_remove()。

header("Content-Type:
application/json")。)

header(&#39;状态。
&#39;
.
$httpStatus)。

http_response_code($httpStatus);

echo json_encode($data);
}
评论(0)

当你试图为API返回JSON响应时,请确保你有适当的头,并确保你返回一个有效的JSON数据。

这里是帮助你从PHP数组或API返回JSON响应的示例脚本。 来自JSON文件.

PHP脚本(代码)。

<?php

// 设置必要的标题
header(&#39;Content-Type:
application/json;
charset=utf-8&#39;)。
header(&#39;Access-Control-Allow-Origin:
*&#39;);

/**
* 例子:第一
*
* 从JSON文件中获取JSON数据,并以JSON响应的形式重新发送。
*/

// 从JSON文件中获取JSON数据
$json = file_get_contents(&#39;response.json&#39;);

// 输出,响应
echo $json;


/**
* 例子:第二
*
* 从PHP数组中建立JSON数据,并以JSON响应的形式返回。
*/

// 或者从数组中建立JSON数据(PHP)。
$json_var = [
&#39;hashtag&#39。
=>
&#39;HealthMatters&#39;。
&#39;id&#39。
=>
&#39;072b3d65-9168-49fd-a1c1-a4700fc017e0&#39;,
&#39;情绪&#39;=>[。
&#39;负面&#39。
=>
44,
&#39;正&#39。
=>
56,
],
&#39;总&#39。
=>
&#39;3400&#39;,
&#39;用户数&#39; => [
[
&#39;profile_image_url&#39;
=>
&#39;http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg&#39;。
&#39;screen_name&#39;
=> &#39;screen_name&#39;。
&#39;rayalrumbel&#39;。
&#39;文字&#39。
=> &#39;文字&#39;。
&#39;Tweet(A),#HealthMatters,因为生活很酷:)我们热爱这种生活,并希望度过更多的时间.&#39;。
&#39;时间戳&#39。
=&gt.,&#39;时间戳&39;。
&#39;{{$timestamp}}&#39;,
],
[
&#39;profile_image_url&#39;
=>
&#39;http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg&#39;。
&#39;screen_name&#39;
=>,&#39;screen_name&#39;。
&#39;mikedingdong&#39;。
&#39;文字&#39。
=>,&#39;文字&#39;。
&#39;微博(B),#健康很重要,因为生命很酷:)我们热爱这种生活,并希望度过更多的时间.&#39;。
&#39;时间戳&#39。
=&gt., &#39;时间戳
&#39;{{$timestamp}}&#39;,
],
[
&#39;profile_image_url&#39;
=>
&#39;http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg&#39;。
&#39;screen_name&#39;
=> &#39;screen_name&#39;。
&#39;ScottMili&#39;。
&#39;文字&#39。
=>
&#39;Tweet(C),#HealthMatters因为生活很酷:)我们热爱这种生活,并希望花费更多的时间.&#39;。
&#39;时间戳&#39。
=&gt.,&#39;时间戳&#39;。
&#39;{{$timestamp}}&#39;,
],
[
&#39;profile_image_url&#39;
=>
&#39;http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg&#39;。
&#39;screen_name&#39;
=> &#39;screen_name&#39;。
&#39;yogibawa&#39;。
&#39;文字&#39。
=&gt.,&#39;文字&#39;。
&#39;Tweet(D),#HealthMatters,因为生活很酷:)我们热爱这种生活,并希望度过更多的时间.&#39;。
&#39;时间戳&#39。
=&gt., &#39;时间戳
&#39;{{$timestamp}}&#39;,
],
],
];

//输出,响应
echo json_encode($json_var);

JSON文件(JSON数据)。

{
"hashtag"。
"HealthMatters"。
"id"。
"072b3d65-9168-49fd-a1c1-a4700fc017e0",
"sentiment":
{
"负"。
44,
"积极"。
56
},
"总数"。
"3400"。
"用户"。
[
{
"file_image_url"。
"http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg"。
"screen_name":
"rayalrumbel"。
"text":
"Tweet(A),#HealthMatters,因为生活很酷:)我们热爱这种生活,想多花点钱"。
"时间戳"。
"{{$timestamp}}"
},
{
"file_image_url"。
"http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg"。
"screen_name": "mikedingdong",:
"mikedingdong"。
"text":
"Tweet(B),#健康很重要,因为生命很酷:)我们热爱这种生活,想多花点时间。"。
"时间戳"。
"{{$timestamp}}"
},
{
"file_image_url"。
"http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg"。
"screen_name":
"ScottMili"。
"text":
"Tweet(C),#HealthMatters因为生活很酷:)我们热爱这种生活,并希望花更多的时间。"。
"时间戳"。
"{{$timestamp}}"
},
{
"file_image_url"。
"http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg"。
"screen_name": "yogibawa",:
"yogibawa"。
"text":
"Tweet(D),#HealthMatters,因为生活很酷:)我们热爱这种生活,想多花点钱"。
"时间戳"。
"{{$timestamp}}"
}
]
}

JSON Screeshot。

[![在此输入图像描述][1]][1]

[1]: https://i.stack.imgur.com/0TYOJ.png

评论(0)