Current Location: Home> Latest Articles> How to Display Text File Content in a PHP Page and Format It

How to Display Text File Content in a PHP Page and Format It

gitbox 2025-06-18

How to Display Text File Content in a PHP Page

When developing PHP applications, reading and displaying the content of a text file is a common requirement. This article will show you how to read a text file in PHP and display its content on a web page, along with how to format the text content using HTML and CSS.

1. Open and Read the File

First, use the fopen() function to open the file.

This code opens the file, reads its content, stores it in the $content variable, and then closes the file.

2. Output the File Content

After reading the file content, the next step is to output it to the page. Use the echo() function to display the content of the variable in the browser:

  
echo $content;  

When you run this code, the full content of the file will be displayed on the page.

3. Add HTML Formatting

For better display, you might need to format the text content with HTML tags. The following example shows how to add HTML tags when displaying the file content:

<span class="fun">" . $content . "</span>
";

In this example, we added a title

tag for the file content, and wrapped it with
</span>
"; echo "";

In this case, we added a CSS style class file-content to enhance the visual display of the file content, including background color, borders, and padding.

Conclusion

Displaying text file content in PHP is quite simple. Use the fopen() function to open the file, the fread() function to read its content, and then the echo() function to output the content. Additionally, you can enhance the presentation of the file content using HTML tags and CSS styles.

gitbox.net
Covering practical tips and function usage in major programming languages to help you master core skills and tackle development challenges with ease.
Repository for Learning Code - gitbox.net