Home > Article > Backend Development > A summary of the correct ways to use php to read files, don't forget to close the file
The fopen method is probably most familiar to former C and C++ programmers, since if you've used those languages, they're more or less tools you've had at your disposal for years. For either of these methods, the file is opened by the standard method of using fopen (the function used to read data), and then closed using fclose, as shown in Listing 1.
List 1. Use fgets to open and read the file
$file_handle = fopen("myfile", "r"); while (!feof($file_handle)) { $line = fgets($file_handle); echo $line; } fclose($file_handle);
Open the file. $file_handle stores a reference to the file itself.
Check if you have reached the end of the file.
Continue reading the file until the end of the file is reached, printing each line as it is read.
Close the file.
Remember these steps.
feof
feof The command will detect whether you have reached the end of the file and return True or False. The loop in Listing 1 continues until you reach the end of the file "myfile". Note: feof will also return False if a URL is being read and the socket times out because there is no more data to read.
fclose
Skipping forward to the end of Listing 1, fclose does the opposite of fopen: it closes the connection to a file or URL. After executing this function, you will no longer be able to read any information from the file or socket.
fgets
Jump back a few lines in Listing 1 and you get to the heart of file handling: the actual reading of the file. The fgets function is the weapon of choice for the first example. It will extract a row of data from the file and return it as a string. After that, you can print or otherwise manipulate the data. The example in Listing 1 will print the entire file fine.
If you decide to limit the size of the processing data block, you can add a parameter to fgets to limit the maximum row length. For example, use the following code to limit the line length to 80 characters: $string = fgets($file_handle, 81);
Recall the "\0" end-of-string terminator in C and set the length to be longer than necessary A number that is one greater than the value. Therefore, if 80 characters are required, the above example uses 81. Make it a habit to add this extra character whenever you use a line limit for this function.
fread
The fgets function is the only one available among multiple file reading functions. It is a more commonly used function because parsing line by line usually makes sense. In fact, several other functions provide similar functionality. However, you don't always need to parse line by line.
You need to use fread at this time. The fread function has a slightly different processing goal than fgets: it tends to read information from binary files (that is, files that do not contain primarily human-readable text). Since the concept of "line" has nothing to do with binary files (logical data structures are generally not terminated by new lines), you must specify the number of bytes that need to be read in. $fh = fopen("myfile", "rb");
$data = fread($file_handle, 4096);
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $fp = fopen($file_path,"r"); $str = fread($fp,filesize($file_path));//指定读取大小,这里把整个文件内容读取出来 echo $str = str_replace("\r\n","<br />",$str); } ?>
Using binary data
Note: The example of this function already uses slightly different parameters than fopen. When working with binary data, always remember to include the b option to fopen. If you skip this, Microsoft® Windows® systems may not process the file correctly because they will handle new lines differently. If you're dealing with a Linux® system (or some other UNIX® variant), this may not seem to matter. But even if you're not developing for Windows, doing so will result in good cross-platform maintainability and is a good practice to follow.
The above code will read 4,096 bytes (4 KB) of data. Note: fread will never read more than 8,192 bytes (8 KB), regardless of how many bytes are specified.
Assuming the file size does not exceed 8 KB, the following code should be able to read the entire file into a string. $fh = fopen("myfile", "rb");
$data = fread($fh, filesize("myfile"));
fclose($fh);
If the file length is greater than this value, you can only use a loop to read the rest in.
fscanf
Back to string processing, fscanf also follows the traditional C file library function. If you're not familiar with it, fscanf reads field data from a file into variables. list ($field1, $field2, $field3) = fscanf($fh, "%s %s %s");
The format string used by this function is described in many places (such as PHP.net) , so we won’t go into details here. Suffice to say, string formatting is extremely flexible. It is worth noting that all fields are placed in the return value of the function. (In C, they are all passed as arguments.)
fgetss
fgetss functions differ from traditional file functions and allow you to better understand the power of PHP. This function functions like the fgets function, but will strip any HTML or PHP tags found, leaving only plain text. View the HTML file shown below.
Sample HTML file
<html> <head><title>My title</title></head> <body> <p>If you understand what "Cause there ain't no one for to give you no pain" means then you listen to too much of the band America</p> </body> </html>
Then filter it through the fgetss function.
Use fgetss
$file_handle = fopen("myfile", "r"); while (!feof($file_handle)) { echo = fgetss($file_handle); } fclose($file_handle);
以下是输出: My title
If you understand what "Cause there ain't no one for to give you no pain"
means then you listen to too much of the band America
fpassthru 函数
无论怎样读取文件,您都可以使用 fpassthru 将其余数据转储到标准输出通道。fpassthru($fh);
此外,此函数将打印数据,因此无需使用变量获取数据。
非线性文件处理:跳跃访问
当然,以上函数只允许顺序读取文件。更复杂的文件可能要求您来回跳转到文件的不同部分。这时就用得着 fseek 了。fseek($fh, 0);
以上示例将跳转回文件的开头。如果不需要完全返回 —— 我们可设定返回千字节 —— 然后就可以这样写:fseek($fh, 1024);
从 PHP V4.0 开始,您有一些其他选项。例如,如果需要从当前位置向前跳转 100 个字节,则可以尝试使用:fseek($fh, 100, SEEK_CUR);
类似地,可以使用以下代码向后跳转 100 个字节:fseek($fh, -100, SEEK_CUR);
如果需要向后跳转至文件末尾前 100 个字节处,则应使用 SEEK_END。fseek($fh, -100, SEEK_END);
在到达新位置后,可以使用 fgets、fscanf 或任何其他方法读取数据。
注:不能将 fseek 用于引用 URL 的文件处理。
回页首
提取整个文件
现在,我们将接触到一些 PHP 的更独特的文件处理功能:用一两行处理大块数据。例如,如何提取文件并在 Web 页面上显示其全部内容?好的,您看到了 fgets 使用循环的示例。但是如何能够使此过程变得更简单?用 fgetcontents 会使过程超级简单,该方法将把整个文件放入一个字符串中。$my_file = file_get_contents("myfilename");
echo $my_file;
虽然它不是最好的做法,但是可以将此命令更简明地写为:echo file_get_contents("myfilename");
本文主要介绍的是如何处理本地文件,但是值得注意的是您还可以用这些函数提取、回显和解析其他 Web 页面。echo file_get_contents("http://127.0.0.1/");
此命令等效于:$fh = fopen("http://127.0.0.1/", "r");
fpassthru($fh);
您一定会查看此命令并认为:“那还是太费力”。PHP 开发人员同意您的看法。因此可以将以上命令缩短为:readfile("http://127.0.0.1/");
readfile 函数将把文件或 Web 页面的全部内容转储到默认的输出缓冲区。默认情况下,如果失败,此命令将打印错误消息。要避免此行为(如果需要),请尝试:@readfile("http://127.0.0.1/");
当然,如果确实需要解析文件,则 file_get_contents 返回的单个字符串可能有些让人吃不消。您的第一反应可能是用 split() 函数将它分解一下。$array = split("\n", file_get_contents("myfile"));
但是既然已经有一个很好的函数为您执行此操作为什么还要这样大费周章?PHP 的 file() 函数一步即可完成此操作:它将返回分为若干行的字符串数组。$array = file("myfile");
应当注意的是,以上两个示例有一点细微差别。虽然 split 命令将删除新行,但是当使用 file 命令(与 fgets 命令一样)时,新行仍将被附加到数组中的字符串上。
但是,PHP 的力量还远不止于此。您可以在一条命令中使用 parse_ini_file 解析整个 PHP 样式的 .ini 文件。
当然,您可能注意到此命令合并了各个部分。这是默认行为,但是您可以通过将第二个参数传递给 parse_ini_file 轻松地修正它:process_sections,这是一个布尔型变量。将 process_sections 设为 True。
$file_array = parse_ini_file("holy_grail.ini", true); print_r $file_array;
并且您将获得以下输出:
Array ( [personal information] => Array ( [name] => King Arthur [quest] => To seek the Holy Grail [favorite color] => Blue ) [more stuff] => Array ( [Samuel Clemens] => Mark Twain [Caryn Johnson] => Whoopi Goldberg ) )
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $fp = fopen($file_path,"r"); $str = ""; $buffer = 1024;//每次读取 1024 字节 while(!feof($fp)){//循环读取,直至读取完整个文件 $str .= fread($fp,$buffer); } $str = str_replace("\r\n","<br />",$str); echo $str; } ?>
The above is the detailed content of A summary of the correct ways to use php to read files, don't forget to close the file. For more information, please follow other related articles on the PHP Chinese website!