


Escape Character Behavior in PHP's Heredoc and Nowdoc Syntaxes
Jul 26, 2025 am 09:45 AMHeredoc handles variable interpolation and basic escape sequences such as \n, \t, \\, \$, but does not process \" or \', while Nowdoc does not perform variable interpolation and any escape processing. All contents, including \n and variables are output literally; 1. Variables such as $name will be replaced, \\n will be parsed as newlines; 2. $name and \n are kept as is; 3. No escape quotes are required for both; 4. The end identifier must occupy one line and no leading spaces. PHP 7.3 allows the use of spaces to indent the end identifier. Therefore, Heredoc is suitable for multi-line strings that need to be formatted, and Nowdoc is suitable for outputting original content such as SQL or JavaScript code.
PHP's Heredoc and Nowdoc syntaxes provide a clean way to define multi-line strings. While they look similar, their handling of escape characters and variable interpolation differences significantly. Understanding how escape characters behave in each is key to using them correctly.

Heredoc: Variables and Escape Sequences Are Processed
Heredoc behaves like a double-quoted string — it allows variable interference and interpretations certain escape sequences , though not all in the way you might expect.
$name = "Alice"; echo <<<EOT Hello $name, This is line one.\nThis is line two. EOT;
Output:

Hello Alice, This is line one. This is line two.
Here, two things happen:
-
$name
is interpolated to"Alice"
-
\n
is interpreted as a newline character
But note: only basic escape sequences like \n
, \r
, \t
, \\
, and \$
are processed in Heredoc. Sequences like \"
or \'
are not special and will appear literally.

echo <<<EOT He said: \"Hello\" EOT;
Output:
He said: \"Hello\"
So even though Heredoc processes some escapes, quotes don't need to be escaped — you can freely use "
or '
without backslashes.
? Bottom line: Heredoc handles
\n
,\t
,\\
,\$
, etc., and interpolates variables. Other escape sequences (like\"
) are ignored and output as-is.
Nowdoc: No Escaping, No Interpolation
Nowdoc is like a single-quoted string — no variable interference , and almost no escape processing at all. It's designed for raw, literal strings.
You define it using single quotes around the identifier:
echo <<<'EOT' Hello $name, This is line one.\nThis is line two. EOT;
Output:
Hello $name, This is line one.\nThis is line two.
Everything is taken literally:
-
$name
is not replaced -
\n
is not converted to a newline - Even
\\
remains as two characters: backslash backslash
The only "escape" behavior in Nowdoc is that you can include the closing identifier ( EOT
in this case) inside the content — as long as it's not on its own line, at the start of the line, with no extra whitespace.
So this is safe:
echo <<<'EOT' This is not the end: EOT here EOT;
But this will end the string prematurely:
echo <<<'EOT' This ends here EOT More text here EOT;
Only the first EOT
closes the string — the rest causes a parse error.
Key Differences Summary
Feature | Heredoc | Nowdoc |
---|---|---|
Variable interpolation | ? Yes | ? No |
Processes \n , \t | ? Yes | ? No (treated literally) |
Escapes like \" | ? Treated literally | ? Treated literally |
Quotes need escaping? | ? No | ? No |
Closening identifier rules | Must be alone on line | Same, but in single quotes |
Practical Tips
- Use Heredoc when you need readable multi-line strings with variables or newlines.
- Use Nowdoc for raw output — like embedding JavaScript, SQL, or configuration snippets without interpolation.
- Don't escape quotes in either syntax — just use them freely.
- Be careful with the closing identifier — it must be at the start of a line with no extra spaces or tabs.
- Indentation: PHP 7.3 allows closing identifier to be indented with spaces only if the heredoc is defined with a closing tag on a new line.
Example with indentation (PHP 7.3):
$message = <<<EOT Line one Line two EOT; // Allowed if EOT is on its own line
Basically, Heredoc gives you flexibility; Nowdoc gives you prediction. Know how escape characters behave in each, and you'll avoid subtle bugs in output formatting.
The above is the detailed content of Escape Character Behavior in PHP's Heredoc and Nowdoc Syntaxes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

preg_quote()escapesregex-specialcharacters,includingbackslashesandthedelimiter,totreatthemasliterals;2.avoiddouble-escapingbypassingrawstrings(e.g.,'C:\path')withoutpre-escapedbackslashes;3.useforwardslashesinpathswhenpossibletoreducebackslashclutter

Heredoc handles variable interpolation and basic escape sequences such as \n, \t, \\, \$, but does not process \" or \', while Nowdoc does not perform variable interpolation and any escape processing. All contents, including \n and variables are output literally; 1. Variables such as $name will be replaced, \\n will be parsed as newlines; 2. $name and \n are kept as is true in Nowdoc; 3. No escape quotes are required for both; 4. The end identifier must occupy one line and no leading spaces. PHP7.3 allows the use of spaces to indent the end identifier. Therefore, Heredoc is suitable for multi-line strings that need to be formatted, and Nowdoc is suitable for outputting original content such as SQL or JavaScript.

Alwaysescapeoutputusingcontext-specificmethods:htmlspecialchars()forHTMLcontentandattributes,rawurlencode()forURLs,andjson_encode()withJSON_HEX_TAG,JSON_HEX_APOS,JSON_HEX_QUOT,andJSON_UNESCAPED_UNICODEforJavaScript.2.UsetemplatingengineslikeTwig,Lara

InBash,singlequotestreatallcharactersliterallywhiledoublequotesallowvariableexpansionandlimitedescaping;inPythonandJavaScript,bothquotetypeshandleescapesthesame,withthechoicemainlyaffectingreadabilityandconveniencewhenembeddingquotes,sousesinglequote

TomasterbackslashesinPHPregex,understandthattwolayersofparsingoccur:PHPprocessesescapesequencesfirst,thentheregexenginedoes;2.UsesinglequotesforregexpatternstoavoidPHPinterpretingescapeslike\basbackspace;3.Indoublequotes,doublethebackslashes(e.g.,&qu

addslashes() should be avoided for SQL escapes because it is not safe and not protected from SQL injection; htmlspecialchars() is used for HTML output to prevent XSS attacks; mysqli_real_escape_string() can be used for string escapes in MySQL queries, but is only a suboptimal option when preprocessing statements cannot be used. 1. addslashes() is outdated and unsafe and should not be used for SQL escape in modern applications; 2. htmlspecialchars() should be used when outputting user input and outputting to HTML to prevent XSS; 3. mysqli_real_escape_string(

SQL injection protection cannot rely on addslashes() because it does not process multi-byte encoding and only escapes finite characters, which is easily bypassed; preprocessing statements (such as parameterized queries for PDO or MySQLi) should be used to separate the data from SQL logic to ensure that the input is not parsed into code; if preprocessing cannot be used, database-specific escape functions (such as real_escape_string and setting the correct character set), identifier whitelist or quotation mark wrapping, integer input casting and other methods should be used according to the context to achieve hierarchical defense.

BackslashesgomissinginPHPbecausetheyaretreatedasescapecharactersindouble-quotedstrings,sotofixthis:1.Usesinglequotesforliteralpathslike'C:\Users\John\Documents',2.Ordoublethebackslashesindoublequotesas"C:\\Users\\\\John\\Documents",3.Prefer
