LoginSignup
1
0

More than 5 years have passed since last update.

PHPでの大容量ファイルの取り扱い(メモ)

Last updated at Posted at 2018-03-01

概要

PHPでのファイルの取り扱い
容量が多き過ぎるとPHPの最大メモリ数の許可をいくら大きくしたところで、メモリが不足してしまう
ポインタを使用すればメモリを気にしなくて済むため、容量があまりに大きいファイルを扱う時用のメモ

コード

先頭からファイルを書き換える

$text = 'Test Message' . PHP_EOL;

$fp = fopen($path, 'r+');
fwrite($fp, $text);
fclose($fp);

特定の位置を書き換える

$offset = strlen($text);

$fp = fopen($path, 'r+');
fseek($fp, $offset);
fwrite($fp, $text);
fclose($fp);

特定の位置(後ろ)から書き換える

$offset = (strlen($text) + 1) * (-1);

$fp = fopen($path, 'r+');
fseek($fp, $offset, SEEK_END);
fwrite($fp, $text);
fclose($fp);

最後のタグを取り除いて書き換える

$tag = '</html>';
$offset = (strlen($tag) + 1) * (-1);

$fp = fopen($path, 'r+');
fseek($fp, $offset, SEEK_END);
fwrite($fp, $text);
fwrite($fp, PHP_EOL . $tag);
fclose($fp);
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0