"when do i use php_eol instead of n and vice-versa ? ajax/jquery client problem" Answer’s

0

The constant PHP_EOL should generally be used for platform-specific output.

  • Mostly for file output really.
  • Actually the file functions already transform n ?? rn on Windows systems unless used in fopen(…, "wb") binary mode.

For file input you should prefer n however. While most network protocols (HTTP) are supposed to use rn, that's not guaranteed.

  • Therefore it's best to break up on n and remove any optional r manually:

    $lines = array_map("rtrim", explode("n", $content));
    

    Or use the file(…, FILE_IGNORE_NEW_LINES) function right away, to leave EOL handling to PHP or auto_detect_line_endings.

  • A more robust and terser alternative is using preg_split() and a regexp:

    $lines = preg_split("/R/", $content);
    

    The R placeholder detects any combination of r + n. So would be safest, and even work for Classic MacOS ? 9 text files (rarely seen in practice).

    Obligatory microoptimization note:
    While regex has a cost, it's surprisingly often speedier than manual loops and string postprocessing in PHP.

And there are a few classic examples where you should avoid PHP_EOL due to its platform-ambiguity:

  • Manual generation of network protocol payloads, such as HTTP over fsockopen().
  • For mail() and MIME construction (which really, you shouldn't do tediously yourself anyway).
  • File output, if you want to consistently write just Unix n newlines regardless of environment.

So use a literal "rn" combination when not writing to files, but preparing data for a specific context that expects network linebreaks.

Wednesday, March 31, 2021
 
christina
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :