LoginSignup
17
17

More than 5 years have passed since last update.

PHPでCSV作るやつを最終的に僕はこうした

Posted at

ダウンロードもしたいし文字列としても取りたい時があるんすよね

なので2通りで返すようにしました。

  • 文字列として返す
  • ダウンロードとして出力する
  • 二次元配列で渡してあげてね。

function arr2csv($arr, $filename = false)
{
    // ダウンロード用として出力する場合は $filename を指定
    if ($filename) {
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename=" . $filename);
        $fp = fopen('php://output', 'w');
        foreach ($arr as $line) {
            mb_convert_variables('sjis-win', 'utf-8', $line);
            fputcsv($fp, $line);
        }
        fclose($fp);
    } else {
        $out = '';
        foreach ($arr as $line) {
            $line_tmp = '"';
            $line_tmp .= implode('","', $line);
            $line_tmp .= '"' . "\n";
            mb_convert_variables('sjis-win', 'utf-8', $line_tmp);
            $out .= $line_tmp;
        }
        return $out;
    }
}

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