Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read in text file line by line php - newline not being detected

I have a php function I wrote that will take a text file and list each line as its own row in a table.

The problem is the classic "works fine on my machine", but of course when I ask somebody else to generate the .txt file I am looking for, it keeps on reading in the whole file as 1 line. When I open it in my text editor, it looks just as how I would expect it with a new name on each line, but its the newline character or something throwing it off.

So far I have come to the conclusion it might have something to do with whatever text editor they are using on their Mac system.

Does this make sense? and is there any easy way to just detect this character that the text editor is recognizing as a new line and replace it with a standard one that php will recognize?

UPDATE: Adding the following line solved the issue.

ini_set('auto_detect_line_endings',true); 

Function:

function displayTXTList($fileName) {     if(file_exists($fileName)) {         $file = fopen($fileName,'r');         while(!feof($file)) {              $name = fgets($file);             echo('<tr><td align="center">'.$name.'</td></tr>');         }         fclose($file);     } else {         echo('<tr><td align="center">placeholder</td></tr>');     }        } 
like image 424
TaRDy Avatar asked May 03 '09 19:05

TaRDy


People also ask

How do you show newlines in Notepad ++?

Open any text file and click on the pilcrow (¶) button. Notepad++ will show all of the characters with newline characters in either the CR and LF format. If it is a Windows EOL encoded file, the newline characters of CR LF will appear (\r\n). If the file is UNIX or Mac EOL encoded, then it will only show LF (\n).

How can I get line number in a string in PHP?

PHP $string = "1e9eea56686511e9052e6578b56ae018"; $data = file_get_contents("example. txt"); $data = explode("\n", $data); for ($line = 0; $line < count($data); $line++) { if (strpos($data[$line], $string) >= 0) { die("String $string found at line number: $line"); } } ?>

How do you write to a new line in PHP?

Use PHP_EOL which outputs \r\n or \n depending on the OS. Don't get in trouble, always use \n unless you want to open the file in a specific OS - if so, use the newline combination of that OS, and not the OS you're running PHP on ( PHP_EOL ).


1 Answers

This doesn't work for you?

http://us2.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings

like image 86
alphazero Avatar answered Sep 21 '22 18:09

alphazero