0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP 】CSV を読み込んで、CSVを書き出してみた

Posted at

初めに

データ分析のために、csvを読み込み処理をする必要があり、csvを扱ったプログラムを書いてみた。まだまだ不慣れのため、参考になるのかわからないが忘備録として残す。

やりたいこと:csvを二次元配列に読み込み、処理して、再度csvに書き出す。

環境

  • Mac OS12.4(M1)
  • PHP 8.1.2

コード

csv_in_out.php
<?php
/*
 *CSVを読み込み => 二次元配列へ
 */

//読み込みたいファイルを設定
$csv_file = file_get_contents('input.csv');

//変数を改行毎の配列に変換
$array_tmp = explode("\n", $csv_file);

$array_csv = [];
foreach ($array_tmp as $key => $value) {
    if ($key == 0) continue; //headerの削除
    if (!$value) continue; //空白行の削除
    $array_csv[] = explode(",", $value);
}

//二次元配列の完成
print_r($array_csv);

/*
 *CSVに書き出し
 */
$output_file = fopen("output.csv", "w");
foreach ($array_csv as $value) {
    //二次元配列を1次元配列へ変換して書き込み
   //配列の個数分繋げる。※もっと良い方法があるかも。詳しい人にご教示頂きたい。
    fwrite($output_file, $value[0] . "," . $value[1] . "," . $value[2] . "," . $value[3] . 
"," . $value[4] . "," . $value[5] . "," . $value[6] . "," . $value[7] . "," . $value[8] . "," . $value[9] . "," . $value[10] . "," . $value[11] . "," . $value[12]  . "\n");
}
fclose($output_file);

終わりに

PHPはcsvを扱える関数がたくさんあるので、もっと勉強したい。

参考サイト

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?