New line (“\n”) in PHP is not working

前端 未结 7 1176
青春惊慌失措
青春惊慌失措 2020-12-08 22:41

For some strange reason, inserting echo \"\\n\"; and other scape sequence characters are not working for me, that\'s why I am just using

相关标签:
7条回答
  • 2020-12-08 23:08

    You should be looking for nl2br(). This will add line breaks (<br>) to your output which will be rendered by the browser; newlines are not.

    0 讨论(0)
  • 2020-12-08 23:13

    If you are working with HTML (viewing the result in browser for example) you have to use the HTML way of linebreaks which is: <br>

    0 讨论(0)
  • 2020-12-08 23:15

    The echo "\n" is probably working, just not the way you expect it to.

    That command will insert a new line character. From the sounds of it, you're using a browser to view your output. Note that if you wrote an HTML file that had a body contents that looked like:

    <p>This
    is
    a
    test </p>
    

    The browser rendering would not include the new lines, and would instead just show "This is a test"

    If you want to see the newlines, you could view source, and you'll see that the source code includes the new lines.

    The rule of thumb is that if you need new lines in a browser, you need to use HTML (e.g. <br />), while if you want it in plain text, you can use the \n

    0 讨论(0)
  • 2020-12-08 23:18

    /n only works if it is used as a simple text but here as we code in a html doc it takes it as a HTML text hence you can use </br> tag instead.

    0 讨论(0)
  • 2020-12-08 23:21

    <br /> is the HTML Tag for new line, whereas "\n" is to output a new line (for real).

    The browser doesn't output a new line each time the HTML file goes to the next line.

    0 讨论(0)
  • 2020-12-08 23:31

    When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.

    <?php
    echo "Line 1\nLine 2";
    ?>
    

    This will render in your browser as:

    Line 1 Line 2
    

    If you need to send plain text to your browser, you can use something like:

    <?php
    header('Content-type: text/plain');
    echo "Line 1\nLine 2";
    ?>
    

    This will output:

    Line 1
    Line 2
    

    PHP Linefeeds (\n) Not Working is referring to sending output to a file rather than the browser.

    0 讨论(0)
提交回复
热议问题