How to Read a Text File in PHP
Reading the contents of a text file is an important part programming, whether you are putting data on a web page, or importing data from a text file into a database. Using PHP's fread and filesize functions, you can place the contents of a entire text file in to a single variable. Using this variable, the text can either be printed to the screen or manipulated in other ways. The fread function also allows for reading only portions of the file.
- Difficulty:
- Easy
Instructions
-
-
1
Open a blank text file. You can use any text editor such as Windows Notepad or GEdit and Kate in Linux.
-
2
Start the php script.
<?php -
3
Place the name of the external text file into a variable.
$textfile = "example.txt"; -
4
Open the external text file for reading.
$file = fopen("example.txt", 'r');
The 'r' parameter tells the fopen function to open the file for reading only. -
5
Place the data from the text file into a variable.
$Data = fread($file, filesize($textfile));
The filesize returns the number of bytes in the variable $textfile. The fread function requires a file ($file), and the number of bytes to read. Combined with the filesize function, it will read the entire file. -
6
Close the external text file.
fclose($file); -
7
Print the file to the screen.
echo $Data; -
8
Close the php program.
?>
The entire program will look like:
<?php
$textfile = "example.txt";
$file = fopen("$textfile", 'r');
$Data = fread($file, filesize($textfile));
fclose($file);
echo $Data;
?> -
9
Save the script with the file extension ".php" in the same directory as your text file. For example, this script will be named example.php.
-
10
Open a terminal window (Linux) or Command Prompt (Windows). In Windows, select "Start" > "All Programs" > "Accessories" > "Command Prompt." In Linux or Unix, open the terminal window under the "System Tools" or "Utilities" sub menu in your operating system's main "Applications" menu.
-
11
Test the script with the following command:
php example.php
-
1
Tips & Warnings
If the php script is stored in a different directory than where your text file is located, you must specify the exact path to the text file in the fopen function.
When used in a web application, this method of reading a file will not print any line breaks.