Page 1 of 1

require() adds new line

Posted: Sat Jan 21, 2012 10:54 am
by vteather
Hello,

When I use:

Code: Select all

<?php
require('myfile.php');
?>
anywhere in my script it adds a new line to the output in the browser.
If it is at the begging of the script, then it adds a new line at the beginning.
It doesn't matter whether I use require/include/require_once/include_once, it always adds new line

This is the content of the included file - file.inc:

Code: Select all

<?php
/*

Comments ...

*/

/* Comment ... */
date_default_timezone_set("Europe/Sofia");
$current_datetime = getdate(time());

define("TODAY", "${current_datetime["mday"]} ${current_datetime["month"]} ${current_datetime["year"]}, ${current_datetime["weekday"]}");
define("YEAR", "${current_datetime["year"]}");
?>
And this is the beginning of the file file.php that includes the above one:

Code: Select all

<?php require_once 'file.inc'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="bg" lang="bg">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
...
<table>My table content</table>
In the browser then when I browse to http://mysite/file.php I see an empty line at the top of the body and immediately after the line comes my table. In other words there is a space between the top of the browser's body and the table.

When I remove from file.php the part <?php require_once 'file.inc'; ?>, the emprty space disappears.
There is no lines after the closing tag "?>" in file.inc. There is nothing at least for me to tell me why this empty space in file.php appears

Re: require() adds new line

Posted: Sat Jan 21, 2012 12:31 pm
by twinedev
The blank line is in file.php. Right at the top.

It starts processing PHP (<?php), it includes file.inc (require_once 'file.inc';), then it stops processing php (?>) so now it will directly output what it sees to the browser. What is the first thing it sees? A newline character. so it outputs that, then it outputs the <!DOCTYPE.... code

Solutions:

Code: Select all

<?php 
    require_once('file.inc');
?><!DOCTYPE ....


Also, as a tip for the file.inc file, so you don't ever have to worry about "is there a blank line at the end", get rid of the closing ?> php tag, it isn't required.

-Greg

Re: require() adds new line

Posted: Sun Jan 22, 2012 4:01 am
by verdi
The problem was with the encoding.
I saved my files with "Encode in UTF-8 without BOM" and the annoying empty line dissapeared!