Response::xml macro

Submitted by localdisk - 3 years ago

Response::xml macro

<?php
// macros.php
Response::macro('xml', function(array $vars, $status = 200, array $header = [], $xml = null)
{
    if (is_null($xml)) {
        $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response/>');
    }
    foreach ($vars as $key => $value) {
        if (is_array($value)) {
            Response::xml($value, $status, $header, $xml->addChild($key));
        } else {
            $xml->addChild($key, $value);
        }
    }
    if (empty($header)) {
        $header['Content-Type'] = 'application/xml';
    }
    return Response::make($xml->asXML(), $status, $header);
});
?>

<?php
// app/start/global.php
// add require macros.php
require app_path() . '/macros.php';
?>

<?php
// How to use
// routes.php
Route::get('api.{ext}', function()
{
    $data = ['status' => 'OK'];
    $ext = File::extension(Request::url());
    return Response::$ext($data);
})->where('ext', 'xml|json');
comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks