Skip to content

Instantly share code, notes, and snippets.

@petehouston
Created November 25, 2016 09:19
Show Gist options
  • Select an option

  • Save petehouston/b9e10d81464e537b341590781a6bfedc to your computer and use it in GitHub Desktop.

Select an option

Save petehouston/b9e10d81464e537b341590781a6bfedc to your computer and use it in GitHub Desktop.
Laravel response xml macro
Response::macro('xml', function(array $vars, $status = 200, array $header = [], $rootElement = 'response', $xml = null)
{
if (is_null($xml)) {
$xml = new SimpleXMLElement('<'.$rootElement.'/>');
}
foreach ($vars as $key => $value) {
if (is_array($value)) {
Response::xml($value, $status, $header, $rootElement, $xml->addChild($key));
} else {
if( preg_match('/^@.+/', $key) ) {
$attributeName = preg_replace('/^@/', '', $key);
$xml->addAttribute($attributeName, $value);
} else {
$xml->addChild($key, $value);
}
}
}
if (empty($header)) {
$header['Content-Type'] = 'application/xml';
}
return Response::make($xml->asXML(), $status, $header);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment