PHP: Examples of Working with Text Files

Examples Function Syntax
 

To create text files

 
Example 1 fopen(): To create a file for writing to or reading from (opens a stream). Use with fclose. $file = fopen(filename, mode); //see p. 259 for available modes
fwrite(): To write strings incrementally to a file created with fopen. How the data is written depends on the mode used in fopen (e.g. replaces or appends existing data). fwrite($file, data[, length]);
Example 2 file_put_contents(): To create and write entire file as string. Does not require fopen. If the file exists, any data it contains is overwritten. $filestring = file_put_contents(filename, string[, options]); //available in version 5; see p. 268 for available options
 

To read an entire text file

 
Example 3

APPLICABLE TO UNIT 4 PROJECT

file(): To read the file into an indexed array. Best when the array needs sorting. Create the file with fopen fwrite, and fclose.

$array = file(filename[, use_include_path]);
Example 4 file_get_contents(): To read the file into a string. Not useful when dealing with arrays. Good to use with file_put_contents for reading and displaying basic strings. $filestring = file_get_contents(filename[, use_include_path]);
  fread(): To read the contents of a file into a string up to a maximum number of bytes. $filestring = fread(filename, length);
  readfile(): To print the contents of a file. Limited use functionally. $filestring = readfile(filename[, use_include_path]);
 

To read a text file incrementally - used with fopen/fclose

 
  fgetc(): To return a single character and move the file pointer to the next character. $string = fgetc(filename);
  fgetcsv(): To return a line, parse the line on a specified delimiter (normally comma separated values - CSV) and move the pointer to the next line. $string = fgetcsv(filename, length[, delimiter, string_enclosure]);
  fgets(): To return a line and move the pointer to the next line. $string = fgets(filename[, length]);
  fgetss(): To returns a line, strip HTML tags, and move the pointer to the next line. $string = fgetss(filename, length[, allowed_tags]);
  stream_get_line: To return a line that ends with a specified delimiter and move the file pointer to the next line. $string = stream_get_line(filename, length, delimiter);
 

To close a stream created with fopen

 
  fclose() fclose(filename);