PHP program to read and display text from a file

By IncludeHelp Last updated : January 7, 2024

Problem statement

Given a file, write a PHP program to read and display text from a file.

Reading and displaying text from a file

To read the text (data) from a file, use the file_get_contents() function and assign the returns value to a variable, then by using the simple echo statement you can display the value of the variable that contains the file's data.

The steps to read and display text from a file are:

  • Initialize a variable with the input file name.
  • Use the file_get_contents() function to read the file's data.
  • Assign it to a variable.
  • And, then print it.

PHP program to read and display text from a file

Here, we have a file "file.txt", we will read and print its text (content).

<?php
// file name (note: file must be there)
$file_name = "file.txt";

// Read its content
$data = file_get_contents($file_name);

// Print the data
echo "File's content is:<br />";
echo $data;
?>

Output:

The output of the above program is:

File's content is:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen book.

To understand the above program, you should have the basic knowledge of the following PHP topics:

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.