php 精简的 JSON 输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6807404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Slim JSON Outputs
提问by max_
I am using the Slim framework with PHP to create a RESTful API for my app. However, I assumed that the framework would have some way of creating easier JSON outputs rather than just exit($jsonEncodedVariable);
.
我正在使用带有 PHP 的 Slim 框架为我的应用程序创建一个 RESTful API。但是,我认为该框架可以通过某种方式创建更简单的 JSON 输出,而不仅仅是exit($jsonEncodedVariable);
.
Am I missing something in the framework, or do I need to use json_encode()
... exit($json)
... for every method?
我是否缺少框架中的某些内容,或者我是否需要使用json_encode()
... exit($json)
... 每种方法?
All of the data is taken out of the my MySQL database and would then be put into a JSON array depending on what REST request was called.
所有数据都从我的 MySQL 数据库中取出,然后根据调用的 REST 请求将其放入 JSON 数组中。
For example, if /api/posts/all
was requested, I would exit()
a JSON array of all the posts which each value for its own key, "value" : key
.
例如,如果/api/posts/all
被请求,我会exit()
使用所有帖子的 JSON 数组,每个帖子的值都对应自己的键"value" : key
.
My question is, is there an easy way, using the slim framework, for exit()
'ing JSON code instead of exiting it as plain text?
我的问题是,有没有一种简单的方法,使用纤薄的框架,来exit()
处理 JSON 代码而不是将其作为纯文本退出?
回答by jmk2142
Why not just use Slim's Response Object? (also... why exit?)
为什么不直接使用 Slim 的 Response Object?(还有……为什么要退出?)
$dataAry = // Some data array
$response = $app->response();
$response['Content-Type'] = 'application/json';
$response['X-Powered-By'] = 'Potato Energy';
$response->status(200);
// etc.
$response->body(json_encode($dataAry));
// Or echo json_encode($dataAry)
Let me preface by saying I still consider myself a noob so if I'm making errors please correct me so I can learn. But, I was playing with a similar problem/question and I thought I might chime in with 2 cents and archive a little more discussion on the matter. The more information there is about Slim on Stack the better.
让我先说我仍然认为自己是个菜鸟,所以如果我犯了错误,请纠正我,以便我学习。但是,我在玩一个类似的问题/问题,我想我可以用 2 美分来回答这个问题,并就此事进行更多讨论。关于 Slim on Stack 的信息越多越好。
I was basically toying with the same thing and I noticed that you were using exit; At first, I was using exit also because echo was including a bunch of HTML and mucking up what was being returned to my AJAX call. When I used exit, it cleanly cut the HTML out but then the Slim response object wasn't changing the response headers as I defined (see above code.)
我基本上是在玩同样的事情,我注意到你正在使用exit;起初,我使用 exit 也是因为 echo 包含了一堆 HTML 并处理了返回给我的 AJAX 调用的内容。当我使用 exit 时,它干净利落地剪掉了 HTML,但是 Slim 响应对象没有像我定义的那样更改响应标头(参见上面的代码。)
What I realized was that this isn't how Slim was designed to work. Use echo, not exit. NOTE - Slim Doc:
我意识到这不是 Slim 设计的工作方式。使用回声,而不是退出。注意 - Slim Doc:
Whenever you echo() content from within a route callback, the echo()'d content is captured >in an output buffer and later appended to the Response body before the HTTP response is >returned to the client.
每当您从路由回调中 echo() 内容时,将在输出缓冲区中捕获 echo() 的内容,然后在 HTTP 响应返回给客户端之前将其附加到响应正文。
That's convenient, but I was not able to echo. What I was messing up on was a bigger problem. Separation of content from behavior. If you're like me, you're setting up a single page application where this code basically sits on index.php. There is initial html that I needed to load up so I included it on that page. What I needed to do was create a cleaner separation. My routing was properly set up and so when people GET '/' the Slim_Views (see Develop Rel.) returns a rendered template of html and js for me. Brilliant!
这很方便,但我无法回应。我搞砸的是一个更大的问题。内容与行为的分离。如果您像我一样,正在设置一个单页应用程序,其中这段代码基本上位于 index.php 上。我需要加载初始 html,因此我将其包含在该页面上。我需要做的是创建一个更清晰的分离。我的路由已正确设置,因此当人们 GET '/' 时,Slim_Views(请参阅 Develop Rel.)为我返回呈现的 html 和 js 模板。杰出的!
Now I have all of Slim's tools at disposal and my code is much much cleaner, separate, manageable, and more compliant with http protocols. I guess this is what frameworks are for. :-)
现在我可以使用 Slim 的所有工具,我的代码更干净、独立、易于管理并且更符合 http 协议。我想这就是框架的用途。:-)
NOTE: I'm not saying all this is what went down on your end, but I thought the question and your setup seemed very similar. It might help another new guy who wanders down this same path.
注意:我并不是说所有这些都是你最后的结果,但我认为这个问题和你的设置看起来非常相似。它可能会帮助另一个在同一条道路上徘徊的新人。
UPDATE:As @alttag mentions, this answer is getting out of date (Slim 2)
更新:正如@alttag 提到的,这个答案已经过时了(Slim 2)
For Slim3, see an answer below or see this page in the documentation
对于 Slim3,请参阅下面的答案或在文档中查看此页面
回答by hakre
header("Content-Type: application/json");
echo json_encode($result);
exit;
回答by jeff_drumgod
Using Slim 3, I'm using this format:
使用 Slim 3,我使用这种格式:
<?php
$app = new \Slim\App();
$app->get('/{id}', function ($request, $response, $args) {
$id = $request->getAttribute('id');
return $response->withJSON(
['id' => $id],
200,
JSON_UNESCAPED_UNICODE
);
});
On request "/123", result JSON with:
在请求“/123”时,结果 JSON 为:
{
id: "123"
}
More infos read here.
更多信息请阅读此处。
[UPDATE]
Added second and third param to withJSON
. Second is The HTTP status code, and third is Json encoding options (best for especial chars and others, for example: print "?" correctly)
[更新] 将第二个和第三个参数添加到withJSON
. 第二个是 HTTP 状态代码,第三个是 Json 编码选项(最适合特殊字符和其他字符,例如:正确打印“?”)
回答by d3nnis
you can extend slim with an output function which output is depending the REST request was called:
您可以使用输出函数扩展 slim,该函数的输出取决于调用的 REST 请求:
class mySlim extends Slim\Slim {
function outputArray($data) {
switch($this->request->headers->get('Accept')) {
case 'application/json':
default:
$this->response->headers->set('Content-Type', 'application/json');
echo json_encode($data);
}
}
}
$app = new mySlim();
and use it like this:
并像这样使用它:
$app->get('/test/', function() use ($app) {
$data = array(1,2,3,4);
$app->outputArray($data);
});
回答by Andreas Bergstr?m
Since everyone has complicated their answers with functions and classes, I'll throw in this simplified answer. The \Slim\Http\Response can do it for you like this:
由于每个人都用函数和类使他们的答案复杂化,因此我将提供这个简化的答案。\Slim\Http\Response 可以像这样为你做:
$app = new \Slim\Slim();
$app->get('/something', function () use ($app) {
$response = $app->response();
$response['Content-Type'] = 'application/json';
$response->status(200);
$response->body(json_encode(['data' => []]));
});
$app->run();
As you're most likely only returning JSON data it might be a good idea to make an appropriate middleware, see http://www.sitepoint.com/best-practices-rest-api-scratch-introduction/.
由于您很可能只返回 JSON 数据,因此制作适当的中间件可能是个好主意,请参阅http://www.sitepoint.com/best-practices-rest-api-scratch-introduction/。
回答by Kristian
I feel your pain. I wanted to make a reusable function, so I made a helpers file, and included this:
我感觉到你的痛苦。我想制作一个可重用的函数,所以我制作了一个帮助文件,并包含了这个:
function toJSON($app, $content) {
$response = $app->response;
$response['Content-Type'] = 'application/json';
$response->body( json_encode($content) );
};
And then I used it like this:
然后我像这样使用它:
$app->get('/v1/users/:id', function($id) use ($app)
{
//instantiate SMM data model
$model = new user_model($site);
//get all docs, or one, depending on if query contains a page ID
$doc = $model->get(array());
//if the object contains main -- we don't need the outer data.
toJSON($app, $doc);
});
Edit: I think it would be really nice if there were already functions like this built into the response object for the popular mime types
编辑:我认为如果已经在流行的 mime 类型的响应对象中内置了这样的函数会非常好
回答by Dharani Dharan A
I think Slim also provides a middleware object which does this automatically so users of that framework doesnt have to write json_decode and encode on every request, its called the
Slim_Middleware_ContentType
object.
我认为 Slim 还提供了一个中间件对象,它会自动执行此操作,因此该框架的用户不必为每个请求编写 json_decode 和编码,它称为
Slim_Middleware_ContentType
对象。
$app->response()->('application/json');
$app->add(new Slim_Middleware_ContentType());
it does the decoding for you. the decoding works great.But for encoding the last post is great.
它为您进行解码。解码效果很好。但是对于编码最后一篇文章很棒。
Thanks, Dharani
谢谢,达拉尼
回答by Sumit Shinde
//JSON output in slim3
$app->get('/users', function($request,$response,$args) {
require 'db_connect.php';
$stmt = $pdo->query("SELECT * FROM users");
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($result));
}
else{
$result = array(
"status" => "false",
"message" => "Result not found"
);
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($result));
}
});
回答by genesis
function _die($array){
echo json_encode($array);
exit;
}
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
_die($array);
回答by k33g_org
why not $response->write(json_encode($dataAry));
instead of echo json_encode($dataAry);
?
为什么不$response->write(json_encode($dataAry));
代替echo json_encode($dataAry);
?