LoginSignup
3
3

More than 5 years have passed since last update.

PHPでCSVファイルから特定の情報を抽出し、新しいCSVファイルを作成する。

Last updated at Posted at 2015-08-28

背景

  • とあるCSVファイルから特定のレコードの特定の項目だけ抽出する必要が出てきたので作成したスクリプト
  • perlとかの方が向いているかも知れないがperlは使ったことがないのでとりあえず実行環境ができているPHPで実装
  • つーか自分があとで使う用のテンプレ

環境

  • Redhat Enterprise Linux 6.5
  • PHP5.3

ソース

<?php
/**
 * ※ 適当にプログラムの説明を書く※
 * 
 * Usage:
 * # php -f $filename [ENTER]
 */

$inFile     = 'hoge.csv';   // 抽出元ファイル
$outFile    = 'fuga.csv';   // 結果ファイル

// ファイルポインタ取得
$inFp   = fopen($inFile, 'rb');
$outFp  = fopen($outFile, 'w');

// ファイル読込み
while ($line = fgets($inFp)) {

    // 入力ファイルのCSVを配列に変換
    $inLineArray    = explode(',', $line);

    // 抽出条件
    if ( 
        // ※ 抽出条件を記載 ※
    ) {

        // 出力ファイルのフォーマットに変換(例)
        $outLineArray   = array(
            0 => $inLineArray[0],
            1 => $inLineArray[0],
            2 => $inLineArray[2],
            3 => $inLineArray[3],
            4 => $inLineArray[6], 
            5 => $inLineArray[9],
            6 => $inLineArray[16],
            7 => $inLineArray[54],
            8 => $inLineArray[55],
        );

        // ファイル出力
        fputs($outFp, implode(",", $outLineArray) . "\r\n");
    }
}

// ファイルポインタ解放
fclose($inFp);
fclose($outFp);

// コンソールに終わったことを知らせる。
echo "done. \n";

スクリプトの実行

php -f $filename
3
3
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
3
3