Question

PHP Newline Characters: Single vs Double Quotes

phpstring-interpolation

Question

In PHP, I am trying to write each client record on a new line:

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo '\r\n';

When I open the generated text file in Notepad, \r\n appears as literal text instead of creating a new line:

1 John Doe\r\n1 John Doe\r\n1 John Doe\r\n

Why is PHP not converting \r\n into a newline, and how should I write a newline correctly?

Short Answer

PHP treats escape sequences differently depending on the quote type. By the end of this page, you will know why '\r\n' is printed literally, when to use "\r\n" or PHP_EOL, and how to write portable text-file lines.

Concept

In PHP, a newline is a character (or, on some systems, a pair of characters), not the visible text \r\n.

The issue is caused by single-quoted strings:

echo '\r\n';

In a single-quoted PHP string, escape sequences such as \n and \r are not interpreted. PHP treats the backslash and following letter as ordinary characters, so it outputs exactly:

\r\n

Use a double-quoted string when you want PHP to interpret newline escape sequences:

echo "\r\n";

For files, PHP also provides PHP_EOL, a constant containing the native line ending for the operating system running PHP:

echo PHP_EOL;

Line endings matter because text editors and operating systems have historically used different conventions:

  • \n is a line feed (LF), common on Linux and macOS.
  • \r\n is carriage return plus line feed (CRLF), traditionally used by Windows.
  • PHP_EOL uses the line ending of the system where PHP is running.

If a file is specifically meant for Windows Notepad, "\r\n" is a safe explicit choice. For general server-side code, PHP_EOL is often clearer and more portable.

Mental Model

Think of quotation marks as instructions for how PHP should read text.

  • Single quotes are like a label printer: print almost everything exactly as written.
  • Double quotes are like an interpreter: recognize special instructions such as \n for a new line and \t for a tab.

So '\r\n' means “print a backslash, r, backslash, and n.” In contrast, "\r\n" means “move to the next line using a Windows-style line ending.”

Take Quiz

Syntax and Examples

Use double quotes for escape sequences:

<?php
$clientId = 1;
$lastName = 'Doe';

echo $clientId;
echo ' ';
echo $lastName;
echo "\r\n";

Output in a text file:

1 Doe

A cleaner approach is to create the whole line at once:

<?php
$clientId = 1;
$lastName = 'Doe';

echo "$clientId $lastName\r\n";

For a platform-native line ending, use PHP_EOL:

<?php
echo "$clientId $lastName" . PHP_EOL;

PHP_EOL is a constant, so it is not inside quotes. Concatenate it with . or include it outside a quoted string.

Step by Step Execution

Consider this code:

<?php
$clientId = 1;
$lastName = 'Doe';
$line = "$clientId $lastName\r\n";
echo $line;

Execution:

  1. $clientId receives the integer 1.
  2. $lastName receives the string Doe.
  3. PHP processes the double-quoted string assigned to $line.
  4. $clientId becomes 1, and $lastName becomes Doe inside the string.
  5. PHP interprets \r as a carriage return and \n as a line feed.
  6. echo outputs 1 Doe, followed by the line-ending characters.

Compare it with this:

<?php
$line = '1 Doe\r\n';
echo $line;

Because the string uses single quotes, PHP does not interpret \r\n. The output visibly contains the four characters \r\n.

Real World Use Cases

Newline characters are used whenever code produces line-based text:

  • CSV and report exports: Write one customer, order, or log entry per line.
  • Application logs: Separate messages so a log viewer can read them easily.
  • Email plain-text bodies: Create readable paragraphs and lists.
  • Command-line scripts: Print each result on its own terminal line.
  • Configuration and data files: Generate .txt, .csv, .env, or other line-oriented formats.
  • API payload preparation: Some protocols and legacy integrations require precise CRLF line endings.

For example, writing a report file:

<?php
$handle = fopen('clients.txt', 'w');

fwrite($handle, "1 Doe\r\n");
fwrite($handle, "2 Smith\r\n");

fclose($handle);
Take Quiz

Real Codebase Usage

In real PHP projects, developers usually avoid many separate echo calls and build complete lines before writing them.

Build a line and write it once

<?php
$line = $clientId . ' ' . $lastName . PHP_EOL;
fwrite($handle, $line);

This is easier to read and reduces the chance of forgetting a separator.

Use fputcsv() for CSV files

Do not manually join CSV values with spaces or commas when data may contain commas, quotes, or newlines:

<?php
$handle = fopen('clients.csv', 'w');
fputcsv($handle, [$clientId, $lastName]);
fclose($handle);

fputcsv() handles CSV escaping correctly.

Keep file format requirements explicit

If an external system specifically requires CRLF, use it intentionally:

<?php
$lineEnding = "\r\n";
fwrite($handle, $record . $lineEnding);

If no external format requires a particular line ending, PHP_EOL is a reasonable default for scripts that produce local text files.

Validate file operations

Production code should check whether a file was opened successfully:

<?php
$handle = fopen('clients.txt', 'w');

if ($handle === false) {
    throw new RuntimeException('Could not open clients.txt for writing.');
}

fwrite($handle, "1 Doe" . PHP_EOL);
fclose($handle);

Common Mistakes

Using single quotes for \n or \r\n

Broken:

echo '\n';
echo '\r\n';

These print the characters literally. Use double quotes instead:

echo "\n";
echo "\r\n";

Putting PHP_EOL inside quotes

Broken:

echo 'PHP_EOL';

That prints the text PHP_EOL. The constant must be used as PHP code:

echo PHP_EOL;

Or concatenate it:

echo 'Client saved.' . PHP_EOL;

Expecting a newline to appear as a visual line break in HTML

A browser collapses ordinary whitespace in HTML. This PHP code does output a newline:

echo "First\nSecond";

But a browser page may display it as a space. For readable HTML, use appropriate markup such as separate paragraphs, or inspect raw output in a text file. Do not use <br> when writing a plain-text file.

Mixing up a text file and PHP output

echo sends data to the response/output stream. It only becomes a file if output is redirected, buffered, or otherwise captured. To write directly to a file, use file_put_contents() or fwrite():

file_put_contents('clients.txt', "1 Doe\r\n");

Assuming every tool handles line endings identically

Modern editors generally recognize LF and CRLF, but some older tools or strict file formats expect one particular convention. Follow the format's documented requirements.

Comparisons

OptionWhat PHP outputsTypical use
'\n'The visible characters \ and nLiteral backslash text
"\n"LF newline characterUnix-style text and most modern tools
'\r\n'The visible characters \r\nLiteral backslash text
"\r\n"CRLF newline charactersWindows-oriented or CRLF-required formats
PHP_EOLOS-native line endingPortable local scripts and generated text files

echo versus file-writing functions

ToolPurpose
echoSends output to the current response/output stream
file_put_contents()Writes a complete string to a file
fwrite()Writes data through an already opened file handle
fputcsv()Writes a correctly escaped CSV row

Choose "\r\n" when the file format explicitly requires CRLF. Choose PHP_EOL when the output should follow the system's normal line-ending convention.

Take Quiz

Cheat Sheet

// Single quotes: escape sequences are usually literal
echo '\n';       // outputs: \n
echo '\r\n';    // outputs: \r\n

// Double quotes: common escape sequences are interpreted
echo "\n";      // LF newline
echo "\r\n";   // CRLF newline

// Native operating-system line ending
echo PHP_EOL;

// Build one text line
echo "$clientId $lastName\r\n";

// Write directly to a file
file_put_contents('clients.txt', "$clientId $lastName" . PHP_EOL);

// Append instead of replacing the file
file_put_contents('clients.txt', "$clientId $lastName" . PHP_EOL, FILE_APPEND);

Key rules:

  • Use double quotes for \n, \r, and \t escape sequences.
  • Use single quotes when you need backslashes to remain literal.
  • Use PHP_EOL without quotes.
  • Use "\r\n" when a Windows or protocol specification explicitly requires CRLF.

FAQ

Why does PHP print \r\n instead of making a new line?

You used single quotes. PHP does not interpret \r and \n as escape sequences inside a single-quoted string.

Should I use \n, \r\n, or PHP_EOL in PHP?

Use "\r\n" when a format requires Windows-style CRLF. Use "\n" for LF-based formats. Use PHP_EOL when a local script should use the operating system's native line ending.

Why does my newline not appear in the browser?

HTML usually collapses whitespace, including newline characters. The newline may be present in the response but not displayed as a visual break. Use semantic HTML elements for page layout.

Does echo create a file in PHP?

No. echo writes to the current output stream. Use file_put_contents(), fwrite(), or another file API to write directly to a file.

Can I write PHP_EOL inside a double-quoted string?

No. "PHP_EOL" is just text. Concatenate the constant instead:

echo 'Hello' . PHP_EOL;

Is \r\n one character?

No. It is two control characters: carriage return (\r) and line feed (\n). Together, they form the traditional Windows line ending.

Does Notepad support \n line endings?

Modern Notepad versions support common line endings, but if you are generating a Windows-specific text file or supporting older software, "\r\n" is the safest explicit choice.

Take Quiz

Mini Project

Description

Build a small PHP client-report exporter. It receives client records, creates one readable line per client, and saves the report to a text file. This demonstrates correct newline handling and direct file output.

Goal

Create a clients.txt file where every client appears on a separate line.

Requirements

Requirement 1

Take Quiz

Keep learning

Related questions

View more