[英]convert object to json data from sql
I want to convert data object to json form, this is my code in symfony, 我想将数据对象转换为json形式,这是我在symfony中的代码,
$connection = $em->getConnection();
$statement = $connection->prepare("select * from contact where id_user=$id");
$statement->execute();
$contacts = $statement->fetchAll();
and in rendering object, I do this, 在渲染对象时,我这样做
return $this->render('...index.html.twig', array('form' => $form->createView(), 'errors' => $form->getErrors(), 'contacts'=>json_encode($contacts)));
but this does not work, any help please 但这不起作用,请提供任何帮助
Try this: 尝试这个:
$contacts= json_encode($contacts);
$Response = new Response(
'...myTemplate.html.twig',
['form' => $form->createView()],
['errors' => $form->getErrors()],
['contacts' => $contacts]
);
$Response->headers->set('Content-Type', 'application/json');
return $oResponse;
Don't forget to use: 不要忘记使用:
use Symfony\Component\HttpFoundation\Response;
Or you can use the JsonResponse Class. 或者,您可以使用JsonResponse类。 Here's the documentation: symfony doc 这是文档: symfony doc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.