Jhim Jhim - 7 months ago 33
PHP Question

Create an XML template for app response

So here is my code...

$app->post(
'/chk_db',
function () use ($app){
require_once 'lib/mysql.php';
$dx = connect_db('MyPhotos');

//XML RESPONSE
$app->response->setStatus(0);
$res = $app->response();
$res['Content-Type'] = 'application/xml';
$view = $app->view();
$view->setTemplatesDirectory('./');
$oArray = array("Status"=> $dx.status, "code" => $dx.code);
return $app->render('chkdb.xml', $oArray);
}
);


I wanna know how to create the chkdb.xml template that can handle my input..
Then will output the following..

<MyPhotos>
<Status>success</Status>
<code>0</code>
</MyPhotos>


Thanks in advance....

EDIT: Answered.. Thanks alexw

Answer

If you use Twig, you can just use the array keys in double-curly-brace placeholders. So if your somearray were:

$somearray = [
    "status" => "success",
    "code" => 0,
    "messages" => [
        "msg1" => "Hello",
        "msg2" => "Goodbye"
    ]
];

Then you just make your XML template (template.xml):

<MyPhotos>
   <Status>{{status}}</Status>
   <code>{{code}}</code>
   <messages>
   {% for message in messages %}
      <message>{{message}}</message>
   {% endfor %}
   </messages>
</MyPhotos>

And render it:

$app->render("template.xml", $somearray);

To use Twig with Slim, you will need to include the Slim-Views package. Configuration instructions are in the README.