How to read the content of a file in PHP

Home > Search > How-to
  by

Let's say you have a file with a few lines of data.

John Smith 1979
Jane Smith 1984
Jack Jones 1975
Betty Jackson 2001

 

The following PHP will create a variable that contains the contents of the file, and then loop through each line in the file, and print each column of each line into an HTML table.

<table>

<?php
# Load the contents of example.txt into a variable called $myfile
$myfile = file('example.txt');

# Loop through each line in $myfile
foreach ($myfile as $lines) {

  # Since the data is separated by a single space, split at a single space
  $column = preg_split('/ /', $lines);

  # Print each column of each line into an HTML table
  echo "<tr>";
  echo "<td>$column[1]</td>";
  echo "<td>$column[2]</td>";
  echo "<td>$column[3]</td>";
  echo "</tr>";
}
?>

</table>

 

The PHP page will produce the following result.

John Smith 1979
Jane Smith 1984
Jack Jones 1975
Betty Jackson 2001

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments