Slim JSON Outputs

前端 未结 17 1699
一整个雨季
一整个雨季 2021-01-30 09:00

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

17条回答
  •  天涯浪人
    2021-01-30 09:51

    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:

    $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/.

提交回复
热议问题