Pages

Read to a text file (PHP)

In the previous lesson, we learned how to use PHP to access the server's filesystem. In this lesson, we will use that information to read from an ordinary text file.
Text files can be extremely useful for storing various kinds of data. They are not quite as flexible as real databases, but text files typically don't require as much memory. Moreover, text files are a plain and simple format that works on most systems.

Open the text file

We use the fopen function to open a text file. The syntax is as follows:

fopen(filename, mode)
 
filename
Name of the file to be opened.
mode
Mode can be set to "r" (reading), "w" (writing) or "a" (appending). In this lesson, we will only read from a file and, therefore, use "r". In the next lesson, we will learn to write and append text to a file.

First, let's try to open unitednations.txt:

 <?php

 // Open the text file
 $f = fopen("unitednations.txt", "r");

 // Close the text file
 fclose($f);

 ?>

Example 1: Read a line from the text file

 

<html>

 <head>
 <title>Reading from text files</title>
 </head>
 <body>

 <?php

 $f = fopen("unitednations.txt", "r");

 // Read line from the text file and write the contents to the client
 echo fgets($f); 

 fclose($f);

 ?>

 </body>
 </html> 
 

Example 2: Read all lines from the text file

  <html>

 <head>
 <title>Reading from text files</title>
 </head>
 <body>

 <?php

 $f = fopen("unitednations.txt", "r");

 // Read line by line until end of file
 while(!feof($f)) { 
     echo fgets($f) . "<br />";
 }

 fclose($f);

 ?>

 </body>
 </html>
 


 
 

No comments:

Flag Counter
| Copyright © 2013 Remote Tutor