超薄JSON输出

时间:2011-07-24 14:30:58

标签: php json frameworks slim

我正在使用Slim框架和PHP为我的应用程序创建RESTful API。但是,我假设框架可以通过某种方式创建更简单的JSON输出,而不仅仅是exit($jsonEncodedVariable);

我在框架中遗漏了什么,或者我是否需要对每种方法使用json_encode() ... exit($json) ...

所有数据都从我的MySQL数据库中取出,然后根据调用的REST请求放入JSON数组中。

例如,如果请求/api/posts/all,我会exit()所有帖子的JSON数组,每个帖子都为自己的键"value" : key赋值。

我的问题是,是否有一种简单的方法,使用slim框架,exit()使用JSON代码而不是以纯文本格式退出?

17 个答案:

答案 0 :(得分:57)

为什么不使用Slim的响应对象? (也......为什么退出?)

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

让我先说我仍然认为自己是一个菜鸟,所以如果我犯了错误,请纠正我,这样我就可以学习。但是,我正在玩一个类似的问题/问题,我想我可能会以2美分的价格收听,并对此事进行更多的讨论。有关Slim on Stack的信息越多越好。

我基本上玩弄同样的东西而且我注意到你正在使用退出;起初,我也在使用exit,因为echo包含了一堆HTML,并且正在查看返回给我的AJAX调用的内容。当我使用exit时,它干净地删除了HTML,但是Slim响应对象没有改变我定义的响应头(参见上面的代码。)

我意识到这不是Slim的设计工作方式。使用echo,而不是退出。注 - Slim Doc:

  

每当你从路由回调中回显()内容时,在输出缓冲区中捕获echo()'d内容&gt;然后在HTTP响应被&gt;返回到客户端之前附加到Response主体。< / p>

这很方便,但我无法回应。我搞砸的是一个更大的问题。将内容与行为分离。如果您像我一样,那么您正在设置一个单页应用程序,其中此代码基本上位于index.php上。我需要加载初始html,因此我将其包含在该页面上。我需要做的是创造一个更清洁的分离。我的路由设置正确,所以当人们获取'/'时,Slim_Views(参见Develop Rel。)会为我返回一个html和js的渲染模板。辉煌!

现在我可以使用Slim的所有工具,我的代码更清晰,更独立,更易于管理,并且更符合http协议。我想这就是框架的用途。 : - )

注意:我并不是说这一切都是你的结果,但我认为问题和你的设置看起来非常相似。这可能有助于另一个沿着同样的道路走下去的新人。

更新:正如@alttag所提到的,这个答案已经过时了(Slim 2)

  

对于Slim3,请参阅下面的答案或see this page in the documentation

答案 1 :(得分:32)

header("Content-Type: application/json");
echo json_encode($result);
exit;

提示:Using The Slim PHP Framework for Developing REST APIs

答案 2 :(得分:24)

使用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
    );
});

根据请求“/ 123”,结果JSON包含:

{
  id: "123"
}

更多信息read here

[UPDATE] 向withJSON添加了第二个和第三个参数。第二个是HTTP状态代码,第三个是Json编码选项(最适合特殊字符和其他字符,例如:print“ã”正确)

答案 3 :(得分:10)

你可以使用输出函数扩展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();

并像这样使用它:

$app->get('/test/', function() use ($app) {
    $data = array(1,2,3,4);
    $app->outputArray($data);
});

答案 4 :(得分:8)

由于每个人都使用函数和类复杂了他们的答案,我会抛出这个简化的答案。 \ 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();

由于您最有可能只返回JSON数据,因此制作适当的中间件可能是个好主意,请参阅http://www.sitepoint.com/best-practices-rest-api-scratch-introduction/

答案 5 :(得分:4)

我感觉到你的痛苦。我想创建一个可重用的函数,所以我创建了一个帮助文件,并包含了这个:

function toJSON($app, $content) {
    $response = $app->response;
    $response['Content-Type'] = 'application/json';
    $response->body( json_encode($content) );
};

然后我像这样使用它:

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

编辑:我认为如果已经在流行的mime类型的响应对象中内置了这样的函数,那将是非常好的

答案 6 :(得分:4)

我认为Slim还提供了一个中间件对象,它自动执行此操作,因此该框架的用户不必编写json_decode并对每个请求进行编码,其称为 Slim_Middleware_ContentType对象。

$app->response()->('application/json');
$app->add(new Slim_Middleware_ContentType());

它为您解码。解码效果很好。但编码最后一篇文章很棒。

谢谢, 陀罗尼

答案 7 :(得分:2)

function _die($array){
   echo json_encode($array);
   exit;
}


$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($result)){
    $array[] = $row;
}

_die($array);

答案 8 :(得分:2)

//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));
    }
});

答案 9 :(得分:1)

我的解决方法是添加“退出”;在json打印结束时,我的开发服务器并不关心,但我的实时服务器不会触发json end事件。我不需要添加标头或使用json_encode。

答案 10 :(得分:1)

为什么不$response->write(json_encode($dataAry));而不是echo json_encode($dataAry);

答案 11 :(得分:0)

使用Slim JSON API https://coderwall.com/p/otcphg/create-a-json-restfull-api-using-slim-framework。你可以用它来处理JSON输出。

答案 12 :(得分:0)

我使用https://github.com/entomb/slim-json-api作为我在Slim 2中编写的API来启用JSON响应。 Init代码看起来像这样:

function APIRequests () {
    $app = \Slim\Slim::getInstance();
    $app->view(new \JsonApiView());
    $app->add(new \JsonApiMiddleware());
}

$app->group('/api', 'APIRequests', function () use ($app) {
    $app->get('/areas/:id', function ($id) use ($app) {
       $app->render(200, Area::find($id));
    });
});

我非常喜欢使用中间件和路由分组的抽象级别,这样可以轻松地将不同的响应类型应用到应用的不同区域。

答案 13 :(得分:0)

[BEFORE]:Content-Type text / html; charset = UTF-8

不使用SOAPUI JSON :(

$this->get('get_all', function ($req, $res, $args) {
    $um = new UserModel();

    return $res
       ->withHeader('Content-Type', 'application/json')
       ->getBody()
       ->write(
        json_encode(
            $um->get_all()
        )
    );
});

[AFTER]:Content-Type application / json; charset = utf-8

使用SOAPUI JSON;)

$this->get('get_all', function ($req, $res, $args) {
    $um = new UserModel();

    return $res
        ->withHeader('Content-type', 'application/json;charset=utf-8')
        ->withJson($um->get_all());

答案 14 :(得分:0)

你可以使用slim3,Slim的Response对象自定义方法withJson($ data,$ status,$ encodingOptions)

$app->get('/hello/{name}', function ($request, $response, $args) {
    $data['msg']='Hello '.$request->getAttribute('name');
    $newResponse = $response->withJson($data);
});

了解更多信息read here.

答案 15 :(得分:0)

这就是我在slim 2中的表现

$app->response->headers->set("Content-Type", 'application/json');
return $app->response->write(json_encode([
    'status' => true,
    'message' => 'Your message'
]));

答案 16 :(得分:-1)

header(“Content-Type:application / json”);     echo json_encode($ data);