纤薄框架:在响应上设置编码


Slim Framework: Setting encoding on response

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

  • $app->contentType('text/html; charset=utf-8');
  • header("Content-Type: application/json");
  • $app->response()->header('Content-Type', 'application/json;charset=utf-8');

我被卡住了。。。:-/

编辑
我已经通过作曲家下载了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();
});

来自 响应/标头/集合标头:

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

试试这个:)

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