Rectangle 27 0

php how to write new lines in CLI and web browser?


header("Content-type: text/plain");

You can set the output's content type to text/plain to make browsers showing the content as, well, plain text like what you will see on CLI

Note
Rectangle 27 0

php how to write new lines in CLI and web browser?


<?php 
if (PHP_SAPI === 'cli') 
{ 
   return PHP_EOL;
} 
else
{
   return "<BR/>";
}
?>
function br() { return (PHP_SAPI === 'cli' ? "\n" : "<br />"); }

Also, @Switz, when answering a question I try and keep it clear rather than short :)

I'd be tempted to use the PHP_EOL constant instead of "\n" to make sure you get the correct line ending for the platform.

You can also define a variable storing the correct new line at the beginning of the script: $br = PHP_SAPI === 'cli' ? "\n" : "<br/>"; and then use that $br whenever you need to write a new line.

You could write a function to return the right thing based on the execution environment:

Note
Rectangle 27 0

php how to write new lines in CLI and web browser?


header("Content-type: text/plain");

You can set the output's content type to text/plain to make browsers showing the content as, well, plain text like what you will see on CLI

Note
Rectangle 27 0

php how to write new lines in CLI and web browser?


<?php
    ob_start();

    $a = 1;
    $b = 2;
    $c = $a + $b;
    echo "Sum of $a and $b is <br /> $c";

    $content = ob_get_clean();
    $type= php_sapi_name();

    if ($type == 'cli' || $type == 'cgi-fcgi') {
        str_replace("<br />", "\n", $content);
    }

    echo $content;

?>

Or the other way around: use \n and call nl2br() if needed

To do so you can write somethink like this:

You can grab the content in a variable and according to platform(page/cli) change into \n

Note