2

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 string 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(); :-)

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@pabloks And what if i need it for Symfony2
You should not use templates to output XML. You can use SimpleXml or XmlWriter instead to make sure the XML is well-formed. Also you don't escape variables in your example (which mentioned tools would do for you).
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.