我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
当前回答
无论何时你试图为API返回JSON响应,或者确保你有适当的标题,也确保你返回一个有效的JSON数据。
下面是示例脚本,它可以帮助您从PHP数组或返回JSON响应 来自JSON文件。
PHP脚本(代码):
<?php
// Set required headers
header('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, response
echo $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, response
echo 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的完整的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 );
您可以使用这个小型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();
?>
无论何时你试图为API返回JSON响应,或者确保你有适当的标题,也确保你返回一个有效的JSON数据。
下面是示例脚本,它可以帮助您从PHP数组或返回JSON响应 来自JSON文件。
PHP脚本(代码):
<?php
// Set required headers
header('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, response
echo $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, response
echo 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:
设置访问安全性也很好——只需将*替换为您希望能够访问它的域。
<?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);
?>
这里有更多的例子:如何绕过Access-Control-Allow-Origin?
根据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错误的内容。