PHP: How do I display the contents of a textfile on my page?

In PHP, you can display the contents of a text file on your webpage using the file_get_contents() function. This function reads the entire file into a string and returns it.

Basic Usage

The simplest way to display file contents is to read the file and echo the result −

<?php
    echo file_get_contents("textfile.txt");
?>

Example with Error Handling

It's good practice to check if the file exists before attempting to read it ?

<?php
    $filename = "sample.txt";
    
    if (file_exists($filename)) {
        $content = file_get_contents($filename);
        echo $content;
    } else {
        echo "File not found!";
    }
?>

Preserving Formatting

If your text file contains line breaks and you want to preserve formatting in HTML, wrap the output in <pre> tags ?

<?php
    $content = file_get_contents("data.txt");
    echo "<pre>" . htmlspecialchars($content) . "</pre>";
?>

Alternative Method Using fopen()

For larger files or more control, you can use fopen() and fread() ?

<?php
    $handle = fopen("largefile.txt", "r");
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            echo $line . "<br>";
        }
        fclose($handle);
    }
?>

Conclusion

Use file_get_contents() for small files and simple reading. For larger files or line-by-line processing, fopen() provides better memory management and control.

Updated on: 2026-03-15T08:49:06+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements