Task Thirteen - File Input Output - PHP Tutorial

This program uses functions to

  • store text into an array
  • save the text in the array to a file on disk
  • load the text in the disk file into a new array
  • display the contents of the new array.

The main program is very short (four lines) because of the way functions have been used. Modularising is a good idea.

Here is a screen shot of the program.

Here is the program code.


<?php

// -----------------------------------------------------------------
// STORE SOME TEXT INTO AN ARRAY
// -----------------------------------------------------------------

function setUpFirstArray(&$anArray)    // & pass parameter by reference
{
  echo "Storing text into an array.\n\n";

  $anArray[] = "the quick brown\r\n";  // \r is the Carriage Return character
  $anArray[] = "fox jumps\r\n";        // \n is the Line Feed character
  $anArray[] = "\r\n";                 // A blank line
  $anArray[] = "over\r\n";             // Unix/Linux does not use \r
  $anArray[] = "the lazy dog";
}

// -----------------------------------------------------------------
// SAVE THE ARRAY TEXT INTO A FILE
// -----------------------------------------------------------------

function saveAnArray($anArray)    // pass parameter by value
{
  echo "Saving the array to a file named foo.txt.\n\n";

  $fp = fopen("foo.txt", "w");

  for ($ii = 0; $ii < count($anArray); $ii++)  
  {
    fputs($fp, $anArray[$ii]);
  }

  fclose ($fp);
}

// -----------------------------------------------------------------
// LOAD THE FILE INTO NEW ARRAY
// -----------------------------------------------------------------

function loadAnArray(&$anArray)    // & pass parameter by reference
{
  echo "Loading the new array from a file named foo.txt.\n\n";

  $fp = fopen("foo.txt", "r");

  while (!feof($fp))
  {
    $in = fgets($fp, 4094);
    $anArray[] = trim($in);
  }

  fclose ($fp);
}

// -----------------------------------------------------------------
// DISPLAY THE CONTENTS OF THE NEW ARRAY
// -----------------------------------------------------------------

function dumpArray($anArray)    // pass parameter by value
{
  echo "Display the contents of the new array.\n\n";

  print_r($anArray);  // Dump the entire array.
}

// -----------------------------------------------------------------
// MAIN PROGRAM
// -----------------------------------------------------------------

setUpFirstArray($foo);  // Store some data into $foo[]
saveAnArray($foo);      // Save $foo[] to a file
loadAnArray($baa);      // Load the file into $baa[]
dumpArray($baa);        // Display the contents of $baa[]

// -----------------------------------------------------------------

 

Code

Explanation

function setUpFirstArray(&$anArray)

This line begins the function that copies data into the array.

$anArray is a formal parameter.

When the function is called from the main program, the name of the array is passed into the function.

By default, PHP functions work on a copy of the data and they leave the original data un-altered.

To make PHP work on the original data, use the & character. (&$anArray)

  • By default PHP passes parameters by value.
    It works work on a copy of the data. The original data is unchanged.
  • Use the & charactrer to pass parameters by reference.
    Work on the original data.

$anArray[] = "the quick brown\r\n";

The $anArray variable has square brackets after it to indicate that it should be treated as an array.

The text between the quotes is added to the next free array position.

"\r\n" adds carriage-return and line-feed characters to the stored text. This starts a new line in the text file that will be saved later.

Unix and Linux do not need the "\r" character.

$fp = fopen("foo.txt", "w");

fclose($fp);

$fp is used to refer to the file. This line links the file name "foo.txt" to the $fp variable. "w" causes the file to be opened for writing data.

This line closes the file when all the writing has finished.

//   START==  STOP=================  STEP==
for ($ii = 0; $ii < count($anArray); $ii++)
{
  fputs($fp, $anArray[$ii]);
}

This for loop starts at 0.
It stops when $ii is equal to or greater than count($anArray).
count($anArray) returns the number of items in the array.
Step causes the counter ($ii) to be increased by one on each repetition.
$ii++ is a shorthand notation that means "add one to $ii"

FilePutString - fputs is a built-in function that writes a text string into a file.
$fp specifies which file to use in case there were several files open at the same time. $anArray holds the text to be written into the file. $ii specifies which position in the array should be used.

$fp = fopen("foo.txt", "r");

while (!feof($fp))
{
  $in = fgets($fp, 4094);
  $anArray[] = trim($in);
}

fclose ($fp);

fopen uses the "r" parameter to open the file for reading data.

The while loop repeats until the end of file is encountered.

! means NOT.

feof($fp) is a built-in function that tests to see if the end of file, $fp, has been reached.

fgets (FileGetString) reads a line of text from the file $fp. 4094 is the maximum line length allowed. This is a limitation built into Windows.

The text from the file is stored into $in.

The trim function is used to strip carriage-return and line-feed characters from $in.

The trimmed result is assigned to the next free location in $anArray.

fclose is used to close the file once all the lines have been read.

print_r($anArray);

print_r is a built-in function that dumps the entire contents of an array. It is useful for debugging programs to check that the array contains the right data.

 

Learning Tasks

Modify your work from lesson twelve. You should already have added "load" and "save" stub functions. (non working functions)

  • Use this example to make your load and save functions fully operational.