PHP Introduction | Using Text Files | Processing File Text Line by Line with file
Then how should you process the text that has been read? PHP provides a function that reads the entire file contents and returns them as an array organized line by line. You can use that function. It is called file.
$variable = file(file specification);
This reads the file specified by the argument and returns an array split and organized line by line. After that, you can retrieve array elements from $variable one by one and process them.
However, in general, this simple form is not used very often. That is because it cannot handle the case where file loading fails. If file loading fails, an error occurs at that point and script execution stops. Then subsequent processing and display are not performed, and the page is cut off midway.
So when there is a possibility of failure, as with file, it is common to write it like this.
$variable = @file(file specification) or failure handling;
If you put the @ symbol before the function name, the script continues without stopping even if execution fails. Also, if you add or after the function, you can perform the processing after or when execution fails.
Now let us look at a simple example.
<?php
$result = "";
$lines = @file("data.txt") or $result = "Could not read the file.";
if ($lines != null){
for($i = 0;$i < count($lines);$i++){
$result .= ($i + 1) . ": " . $lines[$i] . "<br>";
}
}
?>
<!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>
This reads data.txt and displays each line with a line number. Of course, each line is also displayed with line breaks preserved. Here, the file is loaded like this.
$lines = @file("data.txt") or $result = "Could not read the file.";
Then it loops until the loaded $lines array is empty. Whether it is empty is checked like this.
if ($lines != null) {......
null is a reserved word that represents “empty.” It indicates a state where no value has been set in the variable.
If the file is loaded successfully, for($i = 0; $i <count($lines); $i++) reads and processes the text from $lines one line at a time. count($lines) specifies the number of elements in $lines. count is a function that returns the number of elements in the array specified as its argument.