Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache or PHP generating prepending line feed character

I am trying to generate an XML file in a PHP web application:

<?php
... 
header('Content-Type: application/xml');
header('Content-Disposition: attachment; filename=test.xml');
echo "<?xml version=\"1.0\"?>\r\n" . 
...

Bizarrely, when using my servers (PHP Version 5.3.8/Apache 2.2.17 and PHP Version 5.3.10-1/Apache 2.2.22 respectively) a line feed (hex 0a) character is inserted in the beginning of the output, resulting in invalid XML that cannot be used. There's one more online question about this, unresolved.

So if I try echo "bug"; I get 4 bytes, not 3: 0a 62 75 67

However, when using WAMP server locally (PHP 5.4.3/Apache 2.4.2), I get 3 bytes: 62 75 67.

  • Is this a known bug/feature?
  • Is it a configuration issue?
  • Which is to blame, Apache or PHP?
  • Do I have to upgrade my servers? I'd rather not.
like image 838
Gruber Avatar asked Mar 22 '13 19:03

Gruber


2 Answers

It seems like the 0a problem was caused by a trailing Enter character in a PHP file included by my main PHP file. When I removed it from the include file, the 0a character in my output disappeared.

What I find peculiar about this is the different handling of whitespace between PHP versions that I experienced, and the fact that I still got the 0a when testing the community's suggestions.

I have no more time to put research into this, but my advice to people experiencing similar problems is to check whether whitespace in include files may play into the equation. In addition, avoid ending the <?php tag as suggested by Dan below.

like image 22
Gruber Avatar answered Oct 29 '22 19:10

Gruber


Maybe it's an encoding problem. If you are using UTF8 with BOM, there is an extra character at the beginning of the files. Check the encoding of your files, and convert it to UTF8 without BOM to avoid this extra character.

like image 134
Jose Armesto Avatar answered Oct 29 '22 20:10

Jose Armesto