我想从一个PHP脚本中返回JSON。
我可以直接回显结果吗?我必须设置 "Content-Type "头吗?
虽然你通常不需要它,但你可以而且应该设置Content-Type头。
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
如果我没有使用特定的框架,我通常允许一些请求参数来修改输出行为。 一般来说,为了快速排除故障,可以不发送头,或者有时print_r数据有效载荷来监视它(尽管在大多数情况下,它不应该是必要的)。
一段完整的漂亮而清晰的返回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 );
根据json_encode手册,该方法可以返回一个非字符串(false)。
>.方法可以返回一个非字符串(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错误的信息。
尝试用[json_encode][1]对数据进行编码,并用header('Content-type.Application/json');
设置内容类型。
application/json');`。
设置访问安全也是很好的--只需将*替换为你希望能够访问的域名即可。
<?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
如果你需要从php中获取json发送自定义信息,你可以在打印任何其他东西之前添加这个header('Content-Type: application/json');
在打印任何其他东西之前,所以你可以打印你的custome echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';
。
这是一个简单的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格式的结果集,可以这样做。
<?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的一个简单方法是使用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);
你可以使用这个【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();
?>
当你试图为API返回JSON响应时,请确保你有适当的头,并确保你返回一个有效的JSON数据。
这里是帮助你从PHP数组或API返回JSON响应的示例脚本。 来自JSON文件.
PHP脚本(代码)。
<?php
// 设置必要的标题
header('Content-Type:
application/json;
charset=utf-8')。
header('Access-Control-Allow-Origin:
*');
/**
* 例子:第一
*
* 从JSON文件中获取JSON数据,并以JSON响应的形式重新发送。
*/
// 从JSON文件中获取JSON数据
$json = file_get_contents('response.json');
// 输出,响应
echo $json;
/**
* 例子:第二
*
* 从PHP数组中建立JSON数据,并以JSON响应的形式返回。
*/
// 或者从数组中建立JSON数据(PHP)。
$json_var = [
'hashtag'。
=>
'HealthMatters'。
'id'。
=>
'072b3d65-9168-49fd-a1c1-a4700fc017e0',
'情绪'=>[。
'负面'。
=>
44,
'正'。
=>
56,
],
'总'。
=>
'3400',
'用户数' => [
[
'profile_image_url'
=>
'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg'。
'screen_name'
=> 'screen_name'。
'rayalrumbel'。
'文字'。
=> '文字'。
'Tweet(A),#HealthMatters,因为生活很酷:)我们热爱这种生活,并希望度过更多的时间.'。
'时间戳'。
=>.,'时间戳&39;。
'{{$timestamp}}',
],
[
'profile_image_url'
=>
'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg'。
'screen_name'
=>,'screen_name'。
'mikedingdong'。
'文字'。
=>,'文字'。
&#39;微博(B),#健康很重要,因为生命很酷:)我们热爱这种生活,并希望度过更多的时间.&#39;。
'时间戳'。
=>., '时间戳
'{{$timestamp}}',
],
[
'profile_image_url'
=>
'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg'。
'screen_name'
=> 'screen_name'。
'ScottMili'。
'文字'。
=>
&#39;Tweet(C),#HealthMatters因为生活很酷:)我们热爱这种生活,并希望花费更多的时间.&#39;。
'时间戳'。
=>.,'时间戳'。
'{{$timestamp}}',
],
[
'profile_image_url'
=>
'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg'。
'screen_name'
=> 'screen_name'。
'yogibawa'。
'文字'。
=>.,'文字'。
'Tweet(D),#HealthMatters,因为生活很酷:)我们热爱这种生活,并希望度过更多的时间.'。
'时间戳'。
=>., '时间戳
'{{$timestamp}}',
],
],
];
//输出,响应
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]