When PHP Heredoc is Not Working

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

1297 views
d

By. Jacob

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

Solution

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...

_LOADTEMPLATE;[LF]

// 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.

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials