# The following illustrates how to read a file (on the server) line-by-line using PHP. # First, open the file... # The 'r' means the file is being opened for reading. $fp = fopen("some_file.txt", 'r'); # Check to see if the file opened successfully. *Always do this!* # The code below terminates the script if the file didn't open. This might not always be # the most appropriate choice. Often it is necessary to use an 'else' clause on the 'if' # for the "normal" flow, and put other non-trivial error handling inside 'if' clause. if (!$fp) { echo "

Error: Cannot open file...

"; exit; } # Keep reading the file as long as you aren't at the end-of-file. while (!feof($fp)) { # Function fgets() gets a single line of any length from the file. The '\n' character # is still at the end of the line. Normally you want to throw that character away. The # rtrim() function does a right-hand (i.e., the end of the string) trim of "whitespace" # characters. This also removes trailing spaces or tabs (normally a good thing). $line = rtrim(fgets($fp)); # If fgets() returns False (due to an error), rtrim() will return an empty value. In # that case, just iterate around the loop again. [Is this really smart?] if (empty($line)) continue; # Now process the line... } # Finally, close the file... fclose($fp);