file handling
|line by line
a rather lenghty solution for reading a file into an array
full source of line by line [ line 1 - 41 ] | download line by line
| 1 | <?php |
| 2 | // this is the right way of reading a file line by line into an array |
| 3 | $line_array = file('path/to/file.txt'); |
| 4 | ?> |
| 5 | but well, here you go ... |
| 6 | <?php |
| 7 | // GetLine |
| 8 | // Obtain the next line in a given file by reading each character until a r or n is reached. |
| 9 | // @param file a handle returned from fopen for our file. |
| 10 | // @return string the next line in the file. |
| 11 | function getLine($file) |
| 12 | { |
| 13 | // iterate over each character in line. |
| 14 | while (!feof($file)) |
| 15 | { |
| 16 | // append the character to the buffer. |
| 17 | $character = fgetc($file); |
| 18 | $buffer .= $character; |
| 19 | // check for end of line. |
| 20 | if (($character == "n") or ($character == "r")) |
| 21 | { |
| 22 | // checks if the next character is part of the line ending, as in |
| 23 | // the case of windows 'rn' files, or not as in the case of |
| 24 | // mac classic 'r', and unix/os x 'n' files. |
| 25 | $character = fgetc($file); |
| 26 | if ($character == "n") |
| 27 | { |
| 28 | // part of line ending, append to buffer. |
| 29 | $buffer .= $character; |
| 30 | } else { |
| 31 | // not part of line ending, roll back file pointer. |
| 32 | fseek($file, -1, SEEK_CUR); |
| 33 | } |
| 34 | // end of line, so stop reading. |
| 35 | break; |
| 36 | } |
| 37 | } |
| 38 | // return the line buffer. |
| 39 | return $buffer; |
| 40 | } |
| 41 | ?> |
8 hits by 4 users in the last 30 minutes.