I want to make a newline in PHP when using echo. However, if I want it to work on the browser I need to use
and if I’m running it as a script from the command line I need to use n. Is there some way to create a newline that will be interpreted correctly in both?
echo ‘<br>’ or nl2br("n") – makes a newline only in the browser
echo "n" or "rn" – makes a newline only when it is ran through the terminal
3
Answers
You can check for anything that will be absent when the script is called through the terminal and set a constant accordingly. For instance, assume that
$_SERVER['REQUEST_URI']
isnull
when using the terminal, then you could do:You can then use this constant like this:
Alternatively you could check for the presence of HTTP headers and do the same.
you can create a newline that works both in the browser and the command line by detecting the execution environment using php_sapi_name():
Just use
PHP_EOL
or"n"
to make a newline, if you want to display newlines in HTML, use the css stylewhite-space
: