developer tip

PHP 스크립트에서 CSV 파일을 만들고 다운로드하는 방법은 무엇입니까?

copycodes 2020. 10. 4. 11:43
반응형

PHP 스크립트에서 CSV 파일을 만들고 다운로드하는 방법은 무엇입니까?


저는 초보 프로그래머이고 제 질문에 대해 많이 검색했지만 이에 대한 유용한 솔루션이나 자습서를 찾을 수 없습니다.

내 목표는 PHP 배열이 있고 배열 요소가 페이지의 목록에 표시되는 것입니다.

사용자가 원할 경우 배열 요소가있는 CSV 파일을 만들어 다운로드 할 수 있도록 옵션을 추가하고 싶습니다.

나는 이것을하는 방법을 모른다. 나도 많이 검색했습니다. 그러나 아직 유용한 리소스를 찾지 못했습니다.

직접 구현할 수 있도록 튜토리얼이나 솔루션 또는 조언을 제공하십시오. 저는 초보자이므로 구현하기 쉬운 솔루션을 제공하십시오.

내 배열은 다음과 같습니다.

Array
(
    [0] => Array
        (
            [fs_id] => 4c524d8abfc6ef3b201f489c
            [name] => restaurant
            [lat] => 40.702692
            [lng] => -74.012869
            [address] => new york
            [postalCode] => 
            [city] => NEW YORK
            [state] => ny
            [business_type] => BBQ Joint
            [url] => 
        )

)

배열에 대해 내장 된 fputcsv () 를 사용하여 배열에서 올바른 csv 라인을 생성 할 수 있으므로 라인을 반복하고 수집해야합니다. 처럼:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line)
}

브라우저가 "다른 이름으로 저장"대화 상자를 제공하도록하려면 다음과 같은 HTTP 헤더를 보내야합니다 ( rfc 에서이 헤더에 대한 자세한 내용 참조 ).

header('Content-Disposition: attachment; filename="filename.csv";');

함께 모아서:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

다음과 같이 사용할 수 있습니다.

array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);

업데이트 :
(가) 대신에 php://memory당신은 또한 사용할 수 있습니다 php://output파일 기술자에 대한과 추구 및 페지 :

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   

@ complex857 솔루션에 회신 할만한 평판이 충분하지 않습니다. 훌륭하게 작동하지만 추가해야했습니다. Content-Disposition 헤더의 끝에. 이것이 없으면 브라우저는 파일 이름 끝에 두 개의 대시를 추가합니다 (예 : "export.csv"대신 파일이 "export.csv--"로 저장 됨). 아마도 헤더 행의 끝에서 \ r \ n 삭제를 시도 할 것입니다.

올바른 줄은 다음과 같아야합니다.

header('Content-Disposition: attachment;filename="'.$filename.'";');

In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:

header('Content-Type: application/csv; charset=UTF-8');

Also, I find it more elegant to use rewind() instead of fseek():

rewind($f);

Thanks for your solution!


Try... csv download.

<?php 
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
  $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>

Use the below code to convert a php array to CSV

<?php
   $ROW=db_export_data();//Will return a php array
   header("Content-type: application/csv");
   header("Content-Disposition: attachment; filename=test.csv");
   $fp = fopen('php://output', 'w');

   foreach ($ROW as $row) {
        fputcsv($fp, $row);
   }
   fclose($fp);

That is the function i used for my project and it works as expected.

function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
    header( 'Content-Type: application/csv' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '";' );

    // clean output buffer
    ob_end_clean();

    $handle = fopen( 'php://output', 'w' );

    // use keys as column titles
    fputcsv( $handle, array_keys( $array['0'] ) );

    foreach ( $array as $value ) {
        fputcsv( $handle, $value , $delimiter );
    }

    fclose( $handle );

    // flush buffer
    ob_flush();

    // use exit to get rid of unexpected output afterward
    exit();
}

If you're array structure will always be multi-dimensional in that exact fashion, then we can iterate through the elements like such:

$fh = fopen('somefile.csv', 'w') or die('Cannot open the file');

for( $i=0; $i<count($arr); $i++ ){
    $str = implode( ',', $arr[$i] );
    fwrite( $fh, $str );
    fwrite( $fh, "\n" );
}
fclose($fh);

That's one way to do it ... you could do it manually but this way is quicker and easier to understand and read.

Then you would manage your headers something what complex857 is doing to spit out the file. You could then delete the file using unlink() if you no longer needed it, or you could leave it on the server if you wished.

참고URL : https://stackoverflow.com/questions/16251625/how-to-create-and-download-a-csv-file-from-php-script

반응형