我正在尝试将 JSON 请求 $request
转换为数组。
我输出了这样的内容:
^ Symfony\Component\HttpFoundation\Request {#45
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#74
#parameters: array:3 [
"_route" => "app_movie_create"
"_controller" => "App\Controller\MovieController::create"
"_route_params" => []
]
}
+request: Symfony\Component\HttpFoundation\ParameterBag {#96
#parameters: []
}
+query: Symfony\Component\HttpFoundation\ParameterBag {#69
#parameters: array:1 [
"title" => "Homecoming"
]
}
我看过一些教程给出了以下解决方案。
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
}
但在我的例子中,我得到了 null。
我可以这样做。 $request->get('title');
最佳答案
$request->request->all()
将返回请求中发送的所有参数的数组。 $request->query->all()
将返回一个包含已发送的所有查询参数的数组。
json_decode($request->getContent())
仅当发送请求的人在原始正文中向您发送 json 字符串时才有效。就您而言(因为您可以使用 $request->get('title');
),这种情况没有发生。该请求仅包含一些参数,没有原始 json 正文。
关于php - 如何在symfony中将json请求转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59370256/