Getting Laravel to return a View as RSS or XML

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" ?>'; ?>

3 Comments

  • DaBourz

    November 19, 2014

    Better :
    return Response::view(‘hello’)->header(‘Content-Type’, $type);

    Reply
  • larry

    March 7, 2015

    Thanks Andrews. This is cool and i’ll give it a shot!

    Reply
  • Christian

    November 24, 2016

    Thank you Andrew!
    Using PHP print() makes my day!

    Reply

Leave a Reply