Read File Line By Line Using PHP

In this PHP tutorial, We will learn how to read any text/xml file line by line and store it in the database. We will use PHP back-end language for reading and storing data in DB.

What is a File?

A file is simply a resource for storing information on a computer.

Usually, files are used to hold information like:

  • Program configuration options
  • simple information like contact names and phone numbers.
  • photographs, images, etc.

PHP provides set of in-built functions to handle files. Some of the functions are, fopen(), file_exists(), file_get_contents() and etc.

The following list includes some of the fundamental file-related operations.

  • Opening a file
  • To read, write and append data into a file
  • Closing a file

PHP file() Method

The file() method is used to read an entire file into an array. Each array element contains a line from the file with the newline character.

Syntax:

file(filename, flag, context)

  • filename(Required) – Specifies the path to the file to read
  • flag(Optional) – This param will have one of the constants FILE_USE_INCLUDE_PATH, FILE_IGNORE_NEW_LINES, FILE_SKIP_EMPTY_LINES.
  • context(Optional). Specifies the context of the file handle.

Check out other tutorials of PHP File,

Read File Line By Line In PHP

The file() methods to read any text/xml file into an array. We will use this method and read the file line by line. The following code snippet is used for read the file.

Read File in PHP

$lines = file('test.txt');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo "Line #{$line_num} : " . htmlspecialchars($line) . "\n";
}

Result:

line-by-line

You can download source code from the below link.

Leave a Reply

Your email address will not be published. Required fields are marked *