Created
November 25, 2016 09:19
-
-
Save petehouston/b9e10d81464e537b341590781a6bfedc to your computer and use it in GitHub Desktop.
Laravel response xml macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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