Apache or PHP generating prepending line feed character

a 夏天 提交于 2019-12-10 15:33:32

问题


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.

回答1:


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.




回答2:


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.




回答3:


I just ran into this. Took me and team an hour to track down. It's amazing. I love PHP so much.

This is what caused it for us:

<php
  $code = "blah";
?php>

<EOF>

NOTE THE NEWLINE AT THE END OF THE FILE

PHP, in all its transcendent beauty, will interpret this newline as something you're actually trying to send to someone down the wire. It is HTML after all. As a result, a maximum of one newline character will be prepended to your response, even if multiple PHP files in your include path end with a newline.

Take special care that any file you include or require, if they end in a newline, anything you echo or print from your current file will be prepended with a newline.

JUST. AWESOME.




回答4:


In my case it was the newline at the beginning



来源:https://stackoverflow.com/questions/15578271/apache-or-php-generating-prepending-line-feed-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!