Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: empty line from nowhere

Tags:

php

debugging

I have strange error and not sure how to tackle it without wasting too much time. I have a method in my controller which should return xml using:

  header("Content-type: text/xml");
  header("Content-Disposition: attachment; filename=output.xml");
  header("Pragma: no-cache");
  header("Expires: 0");

the thing is that the output is not valid xml because of empty line and I have no idea from where it comes, do you have an idea how to fix this? maybe ignore this empty line or something? I do not want to debug the whole framework... I tried to use var_dump(debug_backtrace()) but I get one big mess probably because of doctrine.

like image 467
mkk Avatar asked Apr 10 '12 20:04

mkk


5 Answers

Almost always, there will be an empty line before or after your <?php ?> tags. If not in your main file, look at your includes.

Also, a little tip... if your file is pure PHP, just start it with <?php and never close the PHP tag. Closing it isn't necessary, and then you avoid blank lines at the end causing you trouble.

like image 174
Brad Avatar answered Nov 10 '22 08:11

Brad


Use ob_clean() which clears buffer that had unwanted newline

like image 31
Masih Avatar answered Nov 10 '22 10:11

Masih


Also, any error messages will be printed into the document before the headers. but sometimes it's hard to find the offender when there's no error. Try this:

ob_start()

Put that first thing in your script, this will ensure that nothing else is output until you call

ob_flush()

Which may not be necessary for you (the ob_flush).

Also, I had this issue a while ago where a script that was included in the middle of another script had a single character after the closing php tag, which caused that single character to push the headers down and make the response invalid.

So I would follow the suggestion made by Brad that you don't use closing php tags unless you have to.

like image 5
Kasapo Avatar answered Nov 10 '22 09:11

Kasapo


I run into this issue from time to time. And it can be very frustrating. :-) Either way - I find this helpful. This will show files with an empty line followed by a php start tag. It will show false positives but helps narrow the search down nicely.

pcregrep -Mron '\n\<\?php' .
like image 2
Bas Kuis Avatar answered Nov 10 '22 08:11

Bas Kuis


I had the same issue and the problem came from a blank line after a closing ?> at the end of one of my php files.

Double check all your php files and remove the closing ?>

like image 1
Olivier Riché Avatar answered Nov 10 '22 08:11

Olivier Riché