Share via:

When PHP Heredoc is Not Working

Heredocs might break for many reasons in PHP, even trimming by editors can sometimes break heredocs.


Edited: 2019-09-20 11:10

I have been using Heredoc for my template files in PHP for a long time, but recently I started using another IDE, and this caused my template files to break for no apparent reason.

It turns out the new editor, in my case Visual Studio Code, was trimming the files before saving them, which would break the template files when loaded by my CMS. Trimming will remove whitespace characters from the end of a file, including the required newline "\n" character, which causes the heredoc to break.

I find it quite silly that something as simple as a missing line feed (LF) at the end of the file could cause the template not to load properly. In any case, there are clearly circumstances where you want to preserve white space.

When the script is run, it may result in an error like this:

Parse error: syntax error, unexpected end of file in...

Or like this within your editor:

Syntax error, unexpected end of file


You can configure your editor so it does not trim your files, or so that it at least adds a single new line (LF) character at the end.

Another option is to add a comment somewhere at the bottom of your file, as this will preserve the required new line after the ending delimiter.

For example:

$template = <<<_LOADTEMPLATE

blah blah blah...


// This comment preserves the "\n" character after the heredoc-end delimiter
// by preventing editors from trimming it away on file-saves...

Also remember, there must not be any characters in front of the start and end demileters, except for semicolon ";" and new line "\n".

In Visual Studio Code, you can configure the editor to always, at least include one new line character at the end. For compatibility with other editors, the comment solution might be better.