skip to Main Content

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


  1. 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'] is null when using the terminal, then you could do:

    if (is_null($_SERVER["REQUEST_URI"])) {
        define("MY_EOL", "n");
    } else {
        define("MY_EOL", "<br>");
    }
    

    You can then use this constant like this:

    echo "First line." . MY_EOL . "Second line.";
    

    Alternatively you could check for the presence of HTTP headers and do the same.

    Login or Signup to reply.
  2. you can create a newline that works both in the browser and the command line by detecting the execution environment using php_sapi_name():

    function newline()
    {
        if (php_sapi_name() === 'cli') {
            echo "n";
        } else {
            echo "<br>";
        }
    }
    
    Login or Signup to reply.
  3. Just use PHP_EOL or "n" to make a newline, if you want to display newlines in HTML, use the css style white-space:

    .preline {
      white-space: pre-line;
    }
    <div>
    default div
    abc
    defg
    hij
    </div>
    
    <div class="preline">
    pre-line div
    abc
    defg
    hij
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search