Slim Framework - 如何在没有模板的情况下输出数组?

Slim Framework - how to output arrays without templates?

如何在 Slim 中写入数组输出?

$app->get('/', function ($request, $response, $args) {
    $array = ['message' => 'Hello World'];
    $response->getBody()->write($array);
    return $response;
});

错误:

Slim Application Error The application could not run because of the following error:

Details

Type: RuntimeException Message: Could not write to stream File: /var/www/slim/vendor/slim/slim/Slim/Http/Stream.php Line: 407

我只想在没有任何模板的情况下将数组输出到屏幕,也json。可能吗?

因为你不能echo一个数组,你需要形成一个字符串然后可以写入输出流。

$response->getBody()->write(print_r($array, true));

print_r的第二个参数是应该return这个值而不是直接打印

PHPDoc 指定 write 方法只接受一个字符串见 \Slim\Http\Response