如何使用Symfony 2和3返回xml或json响应

要在symfony控制器中返回xml响应, 我们需要在控制器中使用Response组件, 然后我们将更改响应的标头以在其上发送特定格式(在这种情况下为xml)。

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;
  }
}

你可以根据需要使用simplexmlelement php函数创建xml节点, 或获取树枝视图的内容。

对于symfony> 2.5的版本, 你可以使用以下代码在控制器中返回json响应, 只需包含JsonResponse类并将其作为普通响应返回即可。

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);
  }
}

如果你使用的是较低版本的symfony, 则可以改用以下代码:

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;
  }
}

玩得开心 !

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_44449.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?