Home Backend Development PHP Tutorial Detailed explanation of examples of reading and splitting large files in PHP

Detailed explanation of examples of reading and splitting large files in PHP

Jul 25, 2016 am 09:11 AM

php读取与分割大文件

在php中,对于文件的读取时,最快捷的方式莫过于使用一些诸如file、file_get_contents之类的函数,简单几行代码即可实现功能。 但当所操作的文件是一个比较大的文件时,这些函数可能就显的力不从心, 下面将从一个需求入手来说明对于读取大文件时,常用的操作方法。 需求如下: 现有一个1G左右的日志文件,大约有500多万行, 用php返回最后几行的内容。

实现方法: 1. 直接采用file函数来操作 注:由于 file函数是一次性将所有内容读入内存,而php为了防止一些写的比较糟糕的程序占用太多的内存而导致系统内存不足,使服务器出现宕机,所以默认情况下 限制只能最大使用内存16M,这是通过php.ini里的memory_limit = 16M来进行设置,这个值如果设置-1,则内存使用量不受限制。 下面是一段用file来取出这具文件最后一行的代码. 整个代码执行完成耗时 116.9613 (s).

  1. $fp = fopen($file, "r");
  2. $num = 10;
  3. $chunk = 4096;
  4. $fs = sprintf("%u", filesize($file));
  5. $max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);
  6. for ($len = 0; $len < $max; $len += $chunk) {
  7. $seekSize = ($max - $len > $chunk) ? $chunk : $max - $len;
  8. fseek($fp, ($len + $seekSize) * -1, SEEK_END);
  9. $readData = fread($fp, $seekSize) . $readData;
  10. if (substr_count($readData, "\n") >= $num + 1) {
  11. preg_match("!(.*?\n){".($num)."}$!", $readData, $match);
  12. $data = $match[0];
  13. break;
  14. }
  15. }
  16. fclose($fp);
  17. echo $data;
复制代码

我机器是2个G的内存,当按下F5运行时,系统直接变灰,差不多20分钟后才恢复过来,可见将这么大的文件全部直接读入内存,后果是多少严重,所以不在万不得以,memory_limit这东西不能调得太高,否则只有打电话给机房,让reset机器了. 2.直接调用linux的tail命令来显示最后几行 在linux命令行下,可以直接使用tail -n 10 access.log很轻易的显示日志文件最后几行,可以直接用php来调用tail命令,执行php代码如下. 整个代码执行完成耗时 0.0034 (s)

  1. file = 'access.log';
  2. $file = escapeshellarg($file); // 对命令行参数进行安全转义
  3. $line = `tail -n 1 $file`;
  4. echo $line;
复制代码

3. 直接使用php的fseek来进行文件操作 这种方式是最为普遍的方式,它不需要将文件的内容全部读入内存,而是直接通过指针来操作,所以效率是相当高效的.在使用fseek来对文件进行操作时,也有多种不同的方法,效率可能也是略有差别的,下面是常用的两种方法. 方法一: 首先通过fseek找到文件的最后一位EOF,然后找最后一行的起始位置,取这一行的数据,再找次一行的起始位置,再取这一行的位置,依次类推,直到找到了$num行。 实现代码如下 整个代码执行完成耗时 0.0095 (s)

  1. function tail($fp,$n,$base=5)
  2. {
  3. assert($n>0);
  4. $pos = $n+1;
  5. $lines = array();
  6. while(count($lines)< =$n){
  7. try{
  8. fseek($fp,-$pos,SEEK_END);
  9. } catch (Exception $e){
  10. fseek(0);
  11. break;
  12. }
  13. $pos *= $base;
  14. while(!feof($fp)){
  15. array_unshift($lines,fgets($fp));
  16. }
  17. }
  18. return array_slice($lines,0,$n);
  19. }
  20. var_dump(tail(fopen("access.log","r+"),10));
复制代码

方法二: 还是采用fseek的方式从文件最后开始读,但这时不是一位一位的读,而是一块一块的读,每读一块数据时,就将读取后的数据放在一个buf里,然后通过换行符(\n)的个数来判断是否已经读完最后$num行数据. 整个代码执行完成耗时 0.0009(s).

  1. $fp = fopen($file, "r");
  2. $line = 10;
  3. $pos = -2;
  4. $t = " ";
  5. $data = "";
  6. while ($line > 0) {
  7. while ($t != "\n") {
  8. fseek($fp, $pos, SEEK_END);
  9. $t = fgetc($fp);
  10. $pos --;
  11. }
  12. $t = " ";
  13. $data .= fgets($fp);
  14. $line --;
  15. }
  16. fclose ($fp);
  17. echo $data
Copy code

Method 3: The entire code execution takes 0.0003(s)

  1. ini_set('memory_limit','-1');
  2. $file = 'access.log';
  3. $data = file($file);
  4. $line = $data[ count($data)-1];
  5. echo $line;
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles