Bootstrap FreeKB - PHP - read file content
PHP - read file content

Updated:   |  PHP articles

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

line one
line two
line three

 

Here is how you can store the contents of foo.txt in an array. In this example, the contents of foo.txt will be stored in the array named $file. You may also want to refer to Getting Started with Arrays in PHP.

var_dump can be used to print the data structure of the array.

var_dump ($file);

 

Which should return something like this.

array(3) { [0]=> string(9) "line one " [1]=> string(9) "line two " [2]=> string(11) "line three " }

 

Or print_r can be used.

print_r ($file);

 

Which should return something like this.

Array ( [0] => line one [1] => line two [2] => line three )

 

And Here is how you can loop through each line in foo.txt and output each line.

<?php
  $file = file('foo.txt');

  foreach ($file as $line) {
     echo "$line <br />";
  }
?>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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