php實現讀取超大檔案的方法_php技巧

來源:互聯網
上載者:User

通常來說在php讀取大檔案的時候,我們採用的方法一般是一行行來講取,而不是一次性把檔案全部寫入記憶體中,這樣會導致php程式卡死,下面就給大家介紹這樣一個例子。

讀取大檔案最後幾行資料:

<?php/** * 取檔案最後$n行 *  * @param string $filename 檔案路徑 * @param int $n 最後幾行 * @return mixed false表示有錯誤,成功則返回字串 */function FileLastLines($filename, $n){   if(!$fp = fopen($filename, 'r')){    echo "開啟檔案失敗,請檢查檔案路徑是否正確,路徑和檔案名稱不要包含中文";    return false;    }  $pos = -2;  $eof = "";  $str = "";  while($n > 0){    while($eof != "n"){      if(!fseek($fp, $pos, SEEK_END)){        $eof = fgetc($fp);        $pos–;        }else{        break;        }      }    $str .= fgets($fp);    $eof = "";    $n–;    }  return $str;  }echo nl2br(FileLastLines('sss.txt', 4));/** * * * 取檔案最後$n行 * *  * @param string $filename 檔案路徑 * * @param int $n 最後幾行 * * @return mixed false表示有錯誤,成功則返回字串 */function FileLastLines($filename, $n){  if(!$fp = fopen($filename, 'r')){    echo "開啟檔案失敗,請檢查檔案路徑是否正確,路徑和檔案名稱不要包含中文";    return false;    }  $pos = -2;  $eof = "";  $str = "";  while($n > 0){    while($eof != "n"){      if(!fseek($fp, $pos, SEEK_END)){        $eof = fgetc($fp);        $pos--;        }else{        break;        }      }    $str .= fgets($fp);    $eof = "";    $n--;    }  return $str;  }echo nl2br(FileLastLines('sss . txt', 4));function tail($fp, $n, $base = 5){  assert($n > 0);  $pos = $n + 1;  $lines = array();  while(count($lines) < = $n){    try{      fseek($fp, - $pos, SEEK_END);      }    catch (Exception $e){      fseek(0);      break;      }    $pos *= $base;    while(!feof($fp)){      array_unshift($lines, fgets($fp));      }    }  return array_slice($lines, 0, $n);  }var_dump(tail(fopen("access.log", "r+"), 10));$fp = fopen($file, "r");$line = 10;$pos = -2;$t = " ";$data = "";while ($line > 0){  while ($t != "n"){    fseek($fp, $pos, SEEK_END);    $t = fgetc($fp);    $pos --;    }  $t = " ";  $data .= fgets($fp);  $line --;  }fclose ($fp);echo $data;?>

讀者可以根據該執行個體特點加以改進和完善,使之更加符合自身應用需求。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.