PHP Introduction | Using Text Files | Loading a File with fgets
First, let us look at “reading a file” with fopen. Here, we will read and display the contents of data.txt with fopen. What we are trying to do is no different from what we have done so far.
Take a look at the example code below.
<?php
$f = @fopen("data.txt",'r') or exit("BREAK");
$result = '';
while(!feof($f)){
$result .= fgets($f,10);
}
fclose($f);
?>
<!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 echo $result; ?></p>
</body>
</html>
Opening a file with fopen and closing it with fclose is exactly as explained earlier. The example also includes “error handling” for fopen. Here, exit is used to end processing. In other words, processing stops at this point, the text passed as the argument, BREAK, is printed to the screen, and the script ends.
The file data is read with a function named fgets. It is called as follows.
$variable = fgets(file pointer);
$variable = fgets(file pointer, number of bytes);
Specify the file pointer to read from as the argument. If the second argument is omitted, one line is read. If an integer is specified as the second argument, that number of bytes is read.
fgets preserves information about the “read position.” If 100 bytes are loaded from a file, that amount of data is read and the read position moves to that point. When fgets is called again, it continues reading from the read position that has moved by 100 bytes. By calling fgets repeatedly, even large files can be read little by little from the beginning.
When loading a file, you also need to check where the end of the file is. Use the feof function for this. If you call it with a file pointer as the argument, it returns true when the file’s read position has reached the end of the file, and false if data still remains. Looking at the example code:
while(!feof($f)){......
This performs a loop. The ! before the variable name is the negation symbol. It is an operator that reverses a Boolean value: true becomes false, and false becomes true. This makes the loop continue while feof($f) is false, meaning there is still data left to read.