7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPで1行ずつ読み込んで何かしら加工したいときのサンプル

Last updated at Posted at 2016-06-25

この記事は移行しました!最新の内容はこちらをご覧ください😀

はじめに

大量のデータを何かしら処理したいときってありますよね。
1行ごとに正規表現とか使って特定の文字列を抽出したいときとか。
たいていはテキストエディタだけで解決できるんですが、
たまーに複雑なことしたくてPHP使いたいときがあります。私はあります。

で、毎回ファイル読み込みとか出力の処理書くのが面倒なので
今後は下記を使おうと思います。

1行ずつ読み込んで何かしら処理して出力するサンプル

$input_filename = 'before.txt'; // 処理したいファイル
$output_filename = 'after.txt'; // 処理後のファイル

$fpr = fopen($input_filename, 'r');
$fpw = fopen($output_filename, 'w');
while ($line = fgets($fpr)) {
    
    // -----
    // ここに$lineに対して何かしらの処理を書く
    // -----
    
    fwrite($fpw, $line);
}
fclose($fpr);
fclose($fpw);
7
8
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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?