質問

作る方法が必要です fputscv 関数一時ファイルを作成し、そのファイルにデータを保存し、実行する代わりに、フラウザにデータをブラウザに書き込みます echo file_get_contents().

役に立ちましたか?

解決

これをPHP DocsのWebサイトで見つけました。最初のコメントは関数リファレンスに基づいています。

function outputCSV($data) {
  $outstream = fopen("php://output", 'w');
  function __outputCSV(&$vals, $key, $filehandler) {
    fputcsv($filehandler, $vals, ';', '"');
  }
  array_walk($data, '__outputCSV', $outstream);
  fclose($outstream);
}

2番目のオプション:

$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
fputcsv($csv, array('blah','blah'));
rewind($csv);

// put it all in a variable
$output = stream_get_contents($csv);

お役に立てれば!

ところで、PHPドキュメントは、物事を理解しようとするとき、常にあなたの最初の停留所でなければなりません。 :-)

他のヒント

PHPサイトに関するコメントによって

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>

元の質問者は「その場でブラウザに書き込みたい」と思っていたので、ファイル名とブラウザのファイルをダウンロードするように求めるダイアログを強制する場合は、注目に値するかもしれません(私の場合は誰も言及しなかったように) 、何かを出力する前に、適切なヘッダーを設定する必要があります fputcsv:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=myFile.csv');

CSVの生産は実際にはそれほど難しいわけではありません(CSVを解析することはもう少し関与しています)。

2D配列をCSVとして記述するためのサンプルコード:

$array = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
];

// If this CSV is a HTTP response you will need to set the right content type
header("Content-Type: text/csv"); 

// If you need to force download or set a filename (you can also do this with 
// the download attribute in HTML5 instead)
header('Content-Disposition: attachment; filename="example.csv"')

// Column heading row, if required.
echo "Column heading 1,Column heading 2,Column heading 3\n"; 

foreach ($array as $row) {
    $row = array_map(function($cell) {
        // Cells containing a quote, a comma or a new line will need to be 
        // contained in double quotes.
        if (preg_match('/["\n,]/', $cell)) {
            // double quotes within cells need to be escaped.
            return '"' . preg_replace('/"/', '""', $cell) . '"';
        }

        return $cell;
    }, $row);

    echo implode(',', $row) . "\n";
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top