php include causes unwanted newline
Asked Answered
T

3

5

(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?

Tyrothricin answered 10/8, 2011 at 7:48 Comment(0)
A
15

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.

Ahouh answered 10/8, 2011 at 8:56 Comment(0)
E
1

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');
Eglantine answered 10/8, 2011 at 9:12 Comment(1)
Yes, the BOM was the problem. For the record, I used Notepad++ to save as "Encode in UTF-8 without BOM".Tyrothricin
B
0

I was in same problem. I found the problem in editor. please edit and save your included file by your notepad or text editor. You will see the change.

Barry answered 12/12, 2013 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.