PHP Introduction | Using Text Files | Loading a Text File with readfile
Reading and displaying the contents of a text file is surprisingly simple in PHP. A function is provided that does exactly this: it loads and displays a specified text file.
Let us try it. First, prepare a text file. Create a text file named data.txt in the same location as the PHP file you will run, which is index.php in this example, and write some text in it. Save it with UTF-8 encoding, just like the PHP file. If the encoding is different, the text may be garbled.
Once the file is ready, create the script. Write the following source code in index.php.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<p><?php readfile("data.txt"); ?></p>
</body>
</html>
When you access the page, the contents of the text file will be displayed as they are.
The PHP script used here is only a single function written in the body section. That part is as follows.
<?php readfile("data.txt"); ?>
readfile is a function that reads the file specified in () and outputs it at that location. By writing this function where you want to display the text, the file contents are output there. There is no need to output it with echo. The readfile function alone is enough.
However, if you actually try it, you will notice that this alone is limited in several ways. First, even if the text contains multiple lines, it is displayed without line breaks. This is because HTML needs a <br> tag to create line breaks. readfile does not automatically convert line breaks to <br>.
Also, because the retrieved text is inserted as is, you cannot use this approach when you want to process part of the text. It simply outputs the entire contents at that location.