Czech version
logolink

< Back to the list of lessons

Working with Text File in PHP

PHPContent of the lesson:

  • Using Text File as a Component of Dynamic Web
  • Source File with Data
  • CSV Format
  • Working with Text File in PHP

Using Text File as a Component of Dynamic Web

One of the parts of dynamic web can be a page which contains information stored inside a text file in the directory structure of the web. It can be a file with simple information which is easier to be stored in a file instead of a database (we do not have to be able to use database - several webhostings do not allow you to use databases).

We will consider a list of employees saved inside a text file and this list will be visualized inside a HTML page.

Source File with Data

The source file for our script is a file from one of table calculators - Microsoft Excel. This file contains a list of employees and is available in two variants:

Because the files from Microsoft Excel are saved in binary mode (source code is not readable as a plain text - try to open it using a text editor like notepad or pspad) you have to adjust the output format to be able to load such a file.

We will export the list of employees to a text file from one of the previous files. The CSV format is the best one for this purpose (you have to select the option to save file as a CSV file). When you save a file into CSV, a text file is created and this file is readable as a plain text. All values from columns are separated by semicolons (usually, but you can change this).

uložení do formátu csv

The text file will contain information about each person (contact) on a new line.

CSV file can be viewed using a notepad or pspad and will look like the following text:

CSV file with data
Zaměstnanci GJŠ Zlín;;;;;;
;;;;;;
Jméno ;Příjmení;Titul;E-mail;Telefon;Fotografie;Zkratka
Eliška;Babíková;;babikova@gjszlin.cz;577007450;babikova.jpg;
Radim;Bárta;Mgr.;barta@gjszlin.cz;577007448;barta.jpg;Bár
Libuše;Beranová;Ing.;beranova@gjszlin.cz;577007434;beranova.jpg;Ber
Milan;Buday;Mgr.;;;;
Oldřiška;Burešová;Mgr.;buresova@gjszlin.cz;577007436;buresova.jpg;Bur
...

If you skip the first three lines you can see that every line contains information about one concrete employee using the structure FirstName;LastName;Title;E-mail;Phone;Photo;Abbreviation. It is possible to process this file easily because all values are perfectly readable.

CSV Format

Take a look on the final appearance of the file in CSV format. This is a simple file format used for exchanging data between table calculators (for example between different systems). Such a file consists of rows and rows consist of columns separated by a character (usually semicolon or comma) - this is also the meaning of CSV = "Comma-separated values". Each item inside one row can be closed to quotation marks (for example because of the fact that the separating character is also inside the text - you have to differ it from the real separating character).

Description of CSV format

Inside the CSV format are saved only text values in the same way as they were displayed in cells of the active list. All characters from all cells will be saved. Columns of data are separated by semicolons and every row will be ended with the line-break character. In case a cell contains the semicolon, its content will be placed inside quotation marks.

All formulas will be converted to text, all formatting, graphic objects, objects and other content will be lost. The euro symbol will be converted to question mark.

Note: If the sheet contains special characters as the copyright symbol (©) and you plan to use the CSV file under different system, you should specify it while saving the file. In case you save the file under Windows and plan to use it under Macintosh, save the list in CSV (Macintosh) format and vice versa.

Source: Microsoft Online Help in application Microsoft Excel 2007

Realize that converting a table which uses another font, color etc. will discard all of these, only plain text is saved. You will be warned about this fact when saving a file to CSV.

upozornění excelu na rizika uložení do csv

For exchange we use rather the xml format nowadays but working with it is a little bit more difficult so CSV file is enough for us.

Working with Text File in PHP

Create a directory and a new test file zobraz-soubor.php inside it. You will place the script to load the exported file here. Save the exported CSV file as zamestnanci.csv inside the subdirectory data.

uložení souborů

The script should open the file and write its output the browser. At first, you should insert the basic HTML structure.

Basic HTML structure of new document

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250" />
<title>List of employees</title>
</head>
<body>

</body>
</html>

Our script will open the file at its current location, browse it line after line and output the current line inside HTML. We can describe its functionality using these steps:

  • Attempt to open the file zamestnanci.csv for reading.
  • It the attempt fails, write an error message, otherwise:
  • Take one row from the file, save it to a variable, write the variable to browser and continue with the next line until the end of file is reached.

Opening file in PHP

To open a file in PHP you can use the function fopen (description). This function needs two parameters:

  • location of file - in our case this is the relative path data/zamestnanci.csv
  • mode of opening file - you specify what are you going to do with the file - in which mode you want to open it (for reading, for writing, for both etc.). In our case we want to read it only so we will use the parameter "r".
Using the function fopen
$soubor=fopen("data/zamestnanci.txt", "r");

Test for file availability in PHP

To check whether the required file exists you can use the function file_exists (description). This function returns TRUE in case that the path exists and FALSE in case that there is no file with this path. This function needs one parameter:

  • location of file - in our case this is the relative path data/zamestnanci.csv
Using the function file_exists
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}

Test for the end of file in PHP

To check whether you got to the end of file in PHP, you can use the function feof (description). This function returns TRUE in case that pointer inside the file is at the end and FALSE in the other case. This function needs one parameter:

  • pointer to file - in our case this is the pointer to the to target file

After the file is successfully opened you will get the pointer to this file -  $soubor and the while cycle will browse the file line after line until the end is reached. In other words: "Until the function foef returns true (which means the end of file) we will continue reading the file line after line.".

Using the function feof
while (!feof($soubor)){
//processing one line
}

Reading one line from the file in PHP

To read one line from a file in PHP you can use the function fgets (description). This function returns a string with length of length-1 (length is optional parameter). This function has one compulsory parameter and one optional parameter:

  • pointer to file - in our case this is the pointer to the to target file
  • length - maximal number of characters which will be read from the line
Using the function fgets to read a line of maximally 5000 characters
while (!feof($soubor)){
$radek = fgets($soubor,5000);
}

The entire script to output a file to browser

We insert the final script inside the marks <?php and ?> inside the body of our page (inside tags <body></body>). The script tries to open a file, then reads it line after line and finally writes the single lines into browser.

Using the function fgets to read a line of maximally 5000 characters
          $nazev_souboru="data/zamestnanci.csv";
          if (file_exists($nazev_souboru)) {
                $soubor=fopen($nazev_souboru, "r");
                if($soubor){
                    while (!feof($soubor)){
                        $radek = fgets($soubor,5000);
                        print($radek);
                        print("<br />");
                    }
                } 
                else 
                {
                    print("File ".$nazev_souboru." cannot be opened for reading.");
                }
           } 
           else 
           {
           print("File ".$nazev_souboru." does not exists.");
           }
        

The final output inside a browser should look like this one:

zobrazeni obsahu souboru v prohlížeči

Additional Texts

Links

Questions

  1. Is it possible to export data from a table calculator to a plain text?
  2. What disadvantages can bring the conversion from a table calculator to a plain text?
  3. Characterize the format CSV.
  4. Which basic functions do you know for reading a text file in PHP?
webdesign, xhtml, css, php - Mgr. Michal Mikláš