Slim Framework:在响应

时间:2016-03-03 09:18:21

标签: php slim

我在响应上设置编码时遇到问题。 尝试:

  • $ app-> contentType(' text / html; charset = utf-8');
  • 标题(" Content-Type:application / json");
  • $ app-> response() - >标题('内容类型',' application / json; charset = utf-8');

我被卡住了......: - /

修改
我已经通过Composer下载了Slim/slim-skeleton

我需要在Route.php中返回JSON:

$app->get('/getStoresByBounds', function () use ($app, $stores) {
    $app->contentType('application/json');

    $myStores = $stores->getStores();

    $app->response()->write(json_encode($myStores));

    $app->stop();
});

2 个答案:

答案 0 :(得分:1)

你可以试试这个:)

// APP
$app = Slim::getInstance();

// CONTENT-TYPE
$app->contentType('application/json');

// STATUS
$app->status(200);

// RESPONSE ARRAY
$response = array();

// PRINT THE RESPONSE ARRAY
$app->response()->write(json_encode($response));
$app->stop();

或尝试通过以下方式访问您的函数内的$app

$app = \Slim\Slim::getInstance();

由于您使用的是V3,因此可以使用:

$app = new \Slim\App();

$app->get('/getStoresByBounds', function (Request $request, Response $response) {

    $myStores = $stores->getStores();

    $response->getBody()->write(json_encode($myStores));

    $newResponse = $response->withHeader(
        'Content-type',
        'application/json; charset=utf-8'
    );

    return $newResponse;
});

答案 1 :(得分:1)

来自The Response/ Headers/ Set Header

$newResponse = $oldResponse->withHeader('Content-type', 'application/json');