Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting newlines in output when using PHP_EOL

Tags:

php

I am putting together a string that I will output to a .srt file:

while ($row = mysql_fetch_array($res)) {
    $srt = $srt . $row['line_number'] . PHP_EOL; 
    $srt = $srt . str_replace(".", ",", $row['start']) . " --> " . str_replace(".", ",", $row['end']) .PHP_EOL ;    
    $srt = $srt . br2nl($row['text']) . PHP_EOL; 
    $srt = $srt . PHP_EOL;  
}

But it seems like PHP_EOL isn't working, because my output is:

100:00:02,107 --> 00:00:05,810you sure

and doesn't have any newlines. I am trying to get my output to be:

1
00:00:02,107 --> 00:00:05,810
you sure

followed by a newline.

It works when testing through localhost on my computer. Could the PHP version on my host be missing support for PHP_EOL?

like image 337
Adam G Avatar asked Jul 17 '12 23:07

Adam G


1 Answers

The PHP manual says the PHP_EOL constant was available since PHP 4.3.10 and PHP 5.0.2

PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2 - http://php.net/manual/en/reserved.constants.php

So test to see if it exists:

var_dump(PHP_EOL); // should output: string(1) " "

OR

var_dump(defined("PHP_EOL")); // should output if exists: bool(true) 

and if it is not defined, just define it manually if you want

define("PHP_EOL", "\n");

OR just use echo "\n" or echo "\r\n"

The other possible reason is when you output the $srt variable in your browser your outputting and the mime type is set in HTML and so you see it as one line, but if you view the source it should be spanned accross multiple lines.

To ensure text output you could echo out a <pre> tag if you want to keep html or at the top of your php file add this line to force text output:

header('Content-Type: text/plain', true);
like image 74
Anthony Hatzopoulos Avatar answered Oct 22 '22 06:10

Anthony Hatzopoulos