You are currently viewing PHP: How to Read Text Files

PHP: How to Read Text Files

Reading text files is a common task in PHP, whether you need to process log files, extract data from text-based sources, or perform other file-related operations. In this beginner’s guide, we will explore how to read text files using PHP. We will cover the basics, including opening and closing files, and reading file contents.

This PHP script reads the contents of a text file named “memo.txt” and outputs it to the browser. Let’s get coding:

<?php

// buffer size constant
const BUFSIZE = 100;

// name of file to be read
$filename = "memo.txt";

/* open the specified file in read mode 'r' */
$fptr = @fopen($filename, "r");

// check if file was opened successfully
if ($fptr == NULL) {

    die("Could not open file $filename for reading.");

}

// loop through file until end of file is reached
while (!feof($fptr)) {

    // read a line of text from the file into the buffer
    $line = fgets($fptr, BUFSIZE);

    // print out the read text
    echo $line . "<br />";

}

/* close the file */
fclose($fptr);

echo "File '$filename' was read successfully.<br />";

I sincerely hope that you find this code helpful. If you wish to learn more about PHP, please subscribe to our newsletter today and continue your PHP learning journey with us!

Leave a Reply