New line n is not working in PHP - Create a New Line in PHP

Updated: September 29th, 2022, 01:14:06 IST
Published: September 28th, 2022
New line n is not working in PHP - Create a New Line in PHP
Title: New line n is not working in PHP - Create a New Line in PHP

Use the PHP newline characters "\n" or "\r\n". The PHP nl2br() method, which places HTML line breaks before all newlines in a string, might be used if you want the line breaks to also be seen in the browser.

Let's take a look at the following example to understand how it works:


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Adding Newlines in PHP</title>
</head>
<body>

<?php

echo "If you view the source of output frame \r\n you will find a newline in this string.";
echo "<br/>";
echo nl2br("You will find the \n newlines in this string \r\n on the browser window.");
?>

</body>
</html>

Output:


If you view the source of output frame you will find a newline in this string.
You will find the
newlines in this string
on the browser window. 

New line ("\n") in PHP is not working

Q1: For some strange reason, inserting echo "\n"; and other scape sequence characters are not working for me, that's why I am just using <br/> instead.

Ans1: It's because you're outputting HTML, and in HTML, "\n" is treated as whitespace.

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 "This is my first line of code (Line 1). \n This is written on Line 2";
?>

This will render in your browser as:

This is my first line of code (Line 1).   This is written on Line 2

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

<?php
header('Content-type: text/plain');
echo "This is my first line of code (Line 1). \n This is written on Line 2";
?>

Output will be:

This is my first line of code (Line 1).   
This is written on Line 2

PHP Linefeeds (\n) Not Working in PHP

Problem occurred: For some reason I can't use \n to create a linefeed when outputting to a file with PHP. It just writes "\n" to the file. I've tried using "\\n" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n but it just appends "\r\n" to the line in the file.

Solution

Use double quotes. "test\n" will work just fine (Or, use 'test' . PHP_EOL).

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

Strings