开发者

How to output xml in symfony?

开发者 https://www.devze.com 2023-02-20 14:43 出处:网络
I have simple output data in an array: $result = array (\'status\'=>true, \'message\'=>\"123123\");

I have simple output data in an array:

$result = array ('status'=>true, 'message'=>"123123");

I would like to output this in xml format. what is the best way to do it in symfony?

I know I can manually put into stri开发者_运维百科ng like this:

return $this->renderText('<xml><status>true</status><message>123123</message></xml>');

But I 'm looking for something much easier. similar to json_encode(); :-)


I think the best way is using a template with the desired format (not the simple one). This way you can easily change format if needed and don't need to be attach to one implementation. Also, using routes, making only one action you can define automatically which template has to use. For example, using a route like:

jobs:
  url: /api/jobs.:sf_format
  param: { module: api, action: list }
  requirements:
    sf_format: (?:xml|json|yaml)

accessing by /api/jobs.xml will use the listSuccess.xml.php, by /api/jobs.json the listSuccess.json.php and by /api/jobs.yaml the listSuccess.yaml.php. Making for each one a template like

<!-- apps/frontend/modules/api/templates/listSuccess.xml.php -->
<?xml version="1.0" encoding="utf-8"?>
<jobs>
<?php foreach ($jobs as $url => $job): ?>
  <job url="<?php echo $url ?>">
<?php foreach ($job as $key => $value): ?>
    <<?php echo $key ?>><?php echo $value ?></<?php echo $key ?>>
<?php endforeach ?>
  </job>
<?php endforeach ?>
</jobs>

You only have to do the proper query on the list action :) This way you have to code a little bit but you can change the format if you want and have multiples output (like xml, json, yaml, etc) simply by making the proper template. Using this idea I made a generic REST service and now I only have to make the query's. This a resume of Jobeet Web Services Example, for more detail check that.


Depending on how complex your XML Output will become, you should definitely use the PHP XML libs. Otherwise its kind of schizophrenic to use a full stack framework but implement the XML part on your own. ;-) For the rest I'll stick with Pabloks answer. You should use the sf_format switch.

0

精彩评论

暂无评论...
验证码 换一张
取 消