A Solution to `syntax error, unexpected $end` in PHP

When PHP encounters the error syntax error, unexpected $end, the debugging steps are as follows:

  1. Check whether the PHP opening tag <?php and closing tag ?> are properly paired in the file.
  2. Pay extra attention to whether ?> appears within comments.

Error example:

Parse error: syntax error, unexpected $end in script.php on line xx

After debugging, it was found that the error occurred in the middle of the file on the following line:

//$str .= "?>\n";

Problem Analysis

The PHP interpreter allows single-line comments before the closing tag. For example:

//$str .= "?>\n";

This is interpreted as:

As a result, adding // to $str .= "?>\n"; to make it a comment inadvertently introduces an extra ?> closing tag, causing the original valid closing tag to become unexpected (unexpected).

Solution

//$str .= "?>\n";