[Solved]: PHP heredoc syntax error, unexpected end of file
  John Mwaniki /   01 Jan 2022

[Solved]: PHP heredoc syntax error, unexpected end of file

Heredoc syntax is one of the four ways of defining a string in PHP. It behaves and works like the double-quotes apart from different syntax and is being used mostly for multi-line strings.

A string with this syntax begins with triple angle brackets "<<<" followed by a delimiter identifier which can be any text of your choice. This is then immediately followed by a newline.

The actual string value then follows which can be a single or multiple lines of text.

The same delimiter identifier follows again in a newline immediately followed by a semi-colon (;) to mark the end of the string.

Example

<?php
$string = <<<ANYTEXT
This is string line 1
And this is line 2
ANYTEXT;

However, you may experience the error below:

PHP Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or heredoc end (T_END_HEREDOC) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in /path/to/file/filename.php on line X

or

PHP Parse error: syntax error, unexpected end of file in /path/to/file/filename.php

or when editing the file in cPanel file editor, the error may be highlighted as below:

Syntax error, unexpected $EOF

The reason why this error occurs is having a space either before or after the closing delimiter identifier. For instance, in our example above, you should ensure that there is no space before or after "ANYTEXT;".

Example

<?php
echo <<<EOD
Hello World!
[space]EOD;[space]

Ensure that there is no space at the places labeled with "[space]" and this should solve it.

Note: The closing delimiter identifier must be alone in a newline followed by a semi-colon (;) and with no whitespace before or after it.

The nowdoc syntax is very similar to the heredoc, only that its delimiter is enclosed in single quotes. In case you experience the unexpected end of file error with the nowdoc syntax, the solution will be the same as that of heredoc.