简体   繁体   中英

Adding new line into text file is not working

My code:

 $file = WWW_ROOT . 'CSV' . DS . 'customer_mobileNumber.txt';
 $handle = fopen($file, "w");
 $content = '';    
 foreach ($customers as $customer) {
     $mobile = trim($customer['Customer']['mobile']);
     $alt_mobile = trim($customer['Customer']['alt_mobile']);
     if (!empty($mobile))
         $content .= $customer['Customer']['mobile'] . PHP_EOL;
     if (!empty($alt_mobile))
         $content .= $customer['Customer']['alt_mobile'] . PHP_EOL;
  }
  fwrite($handle, $content);
  fclose($handle);

Even I try with "\\n" instead of PHP_EOL. But newline is not added into the text file.

Line endings differ on different platforms. Well known are:

  • Linux/Unix: single LF ( \\n )
  • Mac: single CR ( \\r )
  • Windows/DOS: CR followed by LF ( \\r\\n )

The PHP_EOL constant holds the newline constant for the platform the code is executing on . In the case of a remote webserver most likely Linux, so \\n . If you then download that file to a Mac, it doesn't see CR characters, so no newlines are shown. On Windows it depends on the program whether it respects non- \\r\\n newlines.

To prevent this in downloaded files always use full \\r\\n line endings as all 3 platforms and their programs will (usually) parse them correctly. Worst case some programs may show empty lines intermittently if they parse both characters as a newline.

Note that historically \\r\\n is the only right way anyway. On ancient terminals and the good old dot matrix printers the Carriage Return would return cursor or print head (the 'Carriage') to the beginning of the line, and the Newline would advance output a single line. Later platforms simplified this, MS decided to stick with the legacy notation for compatibility reasons. In the end the legacy notation is the only one being handled correctly by all major platforms ironically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM