PHP end tag "?>" [duplicate] PHP end tag "?>" [duplicate] php php

PHP end tag "?>" [duplicate]


This is well documented. From the PHP Manual:

The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

Omitting the closing tag helps you prevent accidental whitespace or newlines from being added to the end of the file.


That's a core PHP feature: unlike other languages, you need to tag PHP code with a special tag (normally <?php) because everything else is considered literal output:

This is not PHP<?phpecho 'This is PHP' . PHP_EOL;?>This is not PHP either
D:\tmp>php test.phpThis is not PHPThis is PHPThis is not PHP either

Although the manual mentions HTML, PHP doesn't really know/care what content-type is outside its tags.

If you forget to close a PHP block when further stuff follows you normally get a syntax error:

This is not PHP<?phpecho 'This is PHP' . PHP_EOL;This is not PHP either
D:\tmp>php test.phpPHP Parse error:  syntax error, unexpected 'is' (T_STRING) in D:\tmp\borrame.php on line 6

Blank lines are a sort of special case because they are valid and almost invisible in almost all languages (PHP, HTML, CSS, JavaScript...) so they often unnoticed.

Once you've removed the ?> tag, your literal blank lines have disappeared from the script output because they've become part of the PHP code (and, as such, they've started to get ignored).

Of course, blank lines are ignored by PHP but not necessarily by whatever you are generating which, as I said, does not need to be HTML: it can be a picture, a PDF document, an Excel spreadsheet. Bogus white lines can be easily avoided by not closing the last PHP block when it's the last part of the file.