I was having problem getting Chrome to recognize a page as RSS or XML feed. Although Firefox has no problem recognizing it, I’m quite sure I’m missing something here.
After some searches, it became clear that the page was returned as a text document. So Chrome simply display the page as HTML. Firefox is smart enough to check the content first before deciding what type of document it is.
In normal PHP circumstances, we would insert header(‘Content-Type’,’text/xml’) before displaying the view. But with Laravel’s blade, that doesn’t work.
The solution was written in Laravel’s documentation, though not obvious.
To return a page as XML, use
return Response::make($content, '200')->header('Content-Type', 'text/xml');
But how to return a view with the header?
Just set the $content to your view. Full code like this:
$content = View::make('home')->with('somevar', $somevar); return Response::make($content, '200')->header('Content-Type', 'text/xml');
Updated (8 Dec 2015):
I’m still getting an error on some server saying that:
syntax error, unexpected 'version' (T_STRING)
Blade will throw an error on line #1 because of the XML opening tag, so use PHP print instead.
<?php print '<?xml version="1.0" encoding="UTF-8" ?>'; ?>
DaBourz
November 19, 2014Better :
return Response::view(‘hello’)->header(‘Content-Type’, $type);
larry
March 7, 2015Thanks Andrews. This is cool and i’ll give it a shot!
Christian
November 24, 2016Thank you Andrew!
Using PHP print() makes my day!
Milan Maharjan
March 9, 2017This is awesome. Thank you so much.
Francesco Parisi
August 6, 2017this worked for me
public function feedrss() {
return response()->view(‘rss’, array(‘rss’=>$this->rss))->header(‘Content-Type’, ‘application/xml’)->header(‘charset’,’utf-8′);
}
https://laravel.com/docs/5.2/responses#other-response-types
christophmkb
November 8, 2017Got the same error, but it only occurs at my online environment. In my localhost testing environment, everything works fine. Not really sure why this error even occurs, but the php print() is a nice workaround, thanks!! 🙂