Skip to content Skip to sidebar Skip to footer

PHP read file line by line to an array

Reading Time: < 1 minute

How can you read file, like text file line by line and get contents to and array using php? This can be using “FILE_IGNORE_NEW_LINES”.Here is a tested example to read text file line by line and create an array.

This is your text file named Student_details.txt

Index No
Name
Marks
Age
Country

Read file line by line.

$StudentDetails= 'Student_details.txt';
$studentArr = file($StudentDetails, FILE_IGNORE_NEW_LINES);
print_r($studentArr);

This is a another method to read file line by line into an array.

$file = fopen("Student_details.txt", "r");
$StudentDetails= array();
while (!feof($file)) {
   $StudentDetails[] = fgets($file);
}
fclose($file);
print_r($StudentDetails);

Additional:

// Using the optional flags parameter since PHP 5
$trimmed = file('Student_details.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);