简体   繁体   中英

How can I get data from mysql database with json encode (Symfony 4)?

Right now I am getting data from the database via Doctrine:

$articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
return $this->render('homepage.html.twig', array('articles' => $articles));

This is working fine. But what I need is to get the data via json encode, because I want to use server-side processing datatables. So I try to use the Serializer

  $encoders = array(new XmlEncoder(), new JsonEncoder());
  $normalizers = array(new ObjectNormalizer());

  $serializer = new Serializer($normalizers, $encoders);
  $articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
  $jsonContent = $serializer->serialize($articles, 'json');

  return $this->render('homepage.html.twig', $jsonContent);

But I get the error message:

Argument 2 passed to Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::render() must be of the type array, string given, called in /Users/work/project/src/Controller/ArticleController.php on line 46 Uncaught PHP Exception Symfony\\Component\\Debug\\Exception\\FatalThrowableError: "Argument 2 passed to Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::render() must be of the type array, string given, called in /Users/work/project/src/Controller/ArticleController.php on line 46" at /Users/work/project/vendor/symfony/framework-bundle/Controller/ControllerTrait.php line 219

So make second argument of render an array:

return $this->render('homepage.html.twig', ['json_content' => $jsonContent]);

In a template:

{{ json_content }}

Though I don't know why you use a template, as there's a json() method which returns single json:

return $this->json($articles); // without using serializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM