Tutorial :When do I use the PHP constant “PHP_EOL”?



Question:

When is it a good idea to use PHP_EOL?

I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?


Solution:1

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.


Solution:2

You use PHP_EOL when you want a new line, and you want to be cross-platform.

This could be when you are writing files to the filesystem (logs, exports, other).

You could use it if you want your generated HTML to be readable. So you might follow your <br /> with a PHP_EOL.

You would use it if you are running php as a script from cron and you needed to output something and have it be formatted for a screen.

You might use it if you are building up an email to send that needed some formatting.


Solution:3

From main/php.h of PHP version 7.1.1 and version 5.6.30:

#ifdef PHP_WIN32  #   include "tsrm_win32.h"  #   include "win95nt.h"  #   ifdef PHP_EXPORTS  #       define PHPAPI __declspec(dllexport)  #   else  #       define PHPAPI __declspec(dllimport)  #   endif  #   define PHP_DIR_SEPARATOR '\\'  #   define PHP_EOL "\r\n"  #else  #   if defined(__GNUC__) && __GNUC__ >= 4  #       define PHPAPI __attribute__ ((visibility("default")))  #   else  #       define PHPAPI  #   endif  #   define THREAD_LS  #   define PHP_DIR_SEPARATOR '/'  #   define PHP_EOL "\n"  





        
Previous
Next Post »