Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php include causes unwanted newline

Tags:

php

php-5.3

(PHP 5.3.6)

I have a php file which contains simply this text - there are no php tags, no trailing newline or extraneous whitespace anywhere:

<div style="border:1px solid green">abc</div>

Now including this from another php file as follows (again, with no extraneous whitespace anywhere):

<div style="border:1px solid red"><?php include "abc.php" ?></div>
<br />
<div style="border:1px solid red"><div style="border:1px solid green">abc</div></div>

I get the result below.

Note that the second method just uses the included content directly. These should both be like the lower one, but as you can see the include causes some wierd kind of newline to be inserted before the content of the included file. I say 'wierd' because when I check the outputted source (via Chrome's view source) there is nothing visible there:

enter image description here

When this section of the page is shown in Chrome's element inspector, there seems to be something there but what exactly it is I can't tell:

enter image description here

It appears to be simply an empty string, but why an empty string would cause newlines and why it would be there in the first place are a mystery. Adding a semicolon to the end of the include statement makes no difference. It occurred to me that it might be a null byte or a 13 (CR) but that should still not cause an HTML line break.

Does anyone know how I can get rid of this unwanted newline?

like image 629
iforce2d Avatar asked Aug 10 '11 07:08

iforce2d


2 Answers

Check the encoding of the included abc.php - does it have a Byte-Order Mark (BOM)? If so, remove it (good code editors allow you to change the file encoding in the Save dialog), that could be the culprit.

like image 142
Jens Roland Avatar answered Nov 16 '22 07:11

Jens Roland


Relying on the Chrome inspector to check the raw output is not a good idea, as the tree is formatted. Use show source is slightly better.

It's most probably not related to include() itself. The first step to take is to open your included file with a hex editor and check whether it is really empty. As Jens Roland pointed it, it can contain a BOM for example, which will be hidden by most text editors.

You can also generate a raw abc.php file with this code and test your code against it:

file_put_contents('abc.php', 'abc');
like image 23
BenMorel Avatar answered Nov 16 '22 07:11

BenMorel