Home » Php » php – Not getting newlines in output when using PHP_EOL

php – Not getting newlines in output when using PHP_EOL

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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);

Answer:

PHP_EOL The correct ‘End Of Line’ symbol for this platform.

So it works on local host because its window and gives a windows line break

You online website is probably on linux and gives a linux line-break

To get a consistent result use "\r\n" instead of PHP_EOL, although I think media players will be a ble to recognize any style of line breaks.