Hello.

(Symfony) is required to output data from mysql in json format.

Getting an article

$em = $this->getDoctrine()->getManager(); $posts = $em->getRepository('BlogBundle:Post')->findBy([], ['id' => 'DESC'], 1); 

Json format

 return new JsonResponse($posts); 

Currently prints [{}] . I need to push all the given articles (title, description, etc.) into an array and output using JsonResponse . How can I do it?

    2 answers 2

    The object in the JSON string is empty because the Post class object contains private properties that cannot be read by the json_encode function.

    Try writing this:

     $post = $this->getDoctrine() ->getRepository('BlogBundle:Post') ->createQueryBuilder('p') ->select('p') ->orderBy('p.id', 'DESC') ->setMaxResults(1) ->getQuery() ->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); return new JsonResponse($post); 
    • All properties of all entities private in Symfony - Durrasell
      $postRepository = $this->getDoctrine()->getRepository('BlogBundle:Post'); $post = $postRepository->findAll(); $response = new JsonResponse(); $response->setData($post); return $response; 
    • In this case, it will also output [{}, {}, {}, {}]. I need these articles in json format. Like this: [{"id": "4", "title": "firstArticle", "description": "firstArticle"}] - TimeToThink
    • what I wrote to you and displays the data in json format. - Durrasell
    • BlogBundle: Post show entity and screen with dd - Durrasell
    • @TimeToThink look like you have no records in the database. Try to display the $posts array before the conversion to json, and everything will become clear. - Hast