w3resource

PHP program to read and display text file contents

PHP File Handling: Exercise-1 with Solution

Write a PHP program to read and display the contents of a text file.

Sample Solution:

PHP Code :

<?php
$filename = "i:/test.txt";

try {
    $fileContents = file_get_contents($filename);
    echo "File Contents:\n";
    echo $fileContents;
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}
?>

Sample Output:

File Contents: PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with PHP. Hope, these exercises help you to improve your PHP coding skills. Currently, following sections are available, we are working hard to add more exercises. Happy Coding!

Explanation:

In the above exercise, we have a $filename variable that holds the name of the text file you want to read and display.

Inside the try block, we use the file_get_contents() function to read the file contents into a string variable called $fileContents.

After that, we use the echo statement to display the contents of the file.

If an error occurs while reading the file, the catch block will catch the exception and display an error message using $e->getMessage().

Flowchart:

Flowchart: PHP program to read and display text file contents.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: PHP File Handling Exercises Home
Next: PHP function to check file existence by path.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.