Learn how to return a response with xml or json format from symfony in a controller.

XML

To return a xml response in a symfony controller, we need to use the Response component in our controller, then we will just change the headers of the response to send a specific format (xml in this case) on it.

<?php 

namespace ourcodeworld\mybundleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class myClass extends Controller
{
  public function xmlresponseAction(){
      $xml = '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
      $xml .= '<mynode><content>Hello</content></mynode>';

      $response = new Response($xml);
      $response->headers->set('Content-Type', 'xml');
        
      return $response;
  }
}

You can useĀ simplexmlelement php function to create you xml node according to your needs or get the content of a twig view.

JSON

With a version of symfony > 2.5 you can use the following code to return a json response in your controller, you only need to include the JsonResponse class and return it as a normal response.

namespace ourcodeworld\mybundleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

class myClass extends Controller
{
  public function jsonresponseAction(){
      $myresponse = array(
        'success' => true,
        'content' => array(
         'main_content' => 'A long string',
         'secondary_content' => 'another string'
        )
      );
        
      return new JsonResponse($myresponse);
  }
}

If you're using a lower version of symfony, you can use the following code instead :

namespace ourcodeworld\mybundleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class myClass extends Controller
{
  public function jsonresponseAction(){
      $myresponse = array(
        'success' => true,
        'content' => array(
         'main_content' => 'A long string',
         'secondary_content' => 'another string'
        )
      );

      $finalResponse = json_encode($myresponse);
        
      $response = new Response($finalResponse);
      $response->headers->set('Content-Type', 'application/json');
        
      return $response;
  }
}

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors