php 如何从php脚本创建和下载csv文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16251625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:46:35  来源:igfitidea点击:

How to create and download a csv file from php script?

phpexport-to-csv

提问by user2302780

I am a novice programmer and I searched a lot about my question but couldn't find a helpful solution or tutorial about this.

我是一名新手程序员,我搜索了很多关于我的问题,但找不到有用的解决方案或教程。

My goal is I have a PHP array and the array elements are showing in a list on the page.

我的目标是我有一个 PHP 数组,数组元素显示在页面上的列表中。

I want to add an option, so that if a user wants, he/she can create a CSV file with array elements and download it.

我想添加一个选项,以便如果用户需要,他/她可以创建一个包含数组元素的 CSV 文件并下载它。

I don't know how to do this. I have searched a lot too. But yet to find any helpful resource.

我不知道该怎么做。我也搜索了很多。但尚未找到任何有用的资源。

Please provide me some tutorial or solution or advice to implement it by myself. As I'm a novice please provide easy to implement solutions.

请为我提供一些教程或解决方案或建议以自己实现它。由于我是新手,请提供易于实施的解决方案。

My array looks like:

我的数组看起来像:

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] => 
        )

)

回答by complex857

You can use the built in fputcsv()for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines. like:

您可以为数组使用内置的fputcsv()以从数组生成正确的 csv 行,因此您必须循环并收集这些行。喜欢:

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

To make the browsers offer the "Save as" dialog you will have to send HTTP headers like this (see more about this header in the rfc):

要使浏览器提供“另存为”对话框,您必须发送这样的 HTTP 标头(在rfc 中查看有关此标头的更多信息):

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

Putting it all together:

把它们放在一起:

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);
}

And you can use it like this:

你可以像这样使用它:

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"
);

Update:
Instead of the php://memoryyou can also use the php://outputfor the file descriptor and do away with the seeking and such:

更新:您还可以使用for 文件描述符
代替 ,并取消搜索等:php://memoryphp://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);
    }
}   

回答by Luxian

I don't have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.

我没有足够的声誉来回复@complex857 解决方案。它工作得很好,但我不得不添加; 在 Content-Disposition 标头的末尾。如果没有它,浏览器会在文件名的末尾添加两个破折号(例如,文件将保存为“export.csv--”而不是“export.csv”)。可能它试图在标题行的末尾清理 \r\n。

Correct line should look like this:

正确的行应该是这样的:

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:

如果 CSV 中包含 UTF-8 字符,则必须通过更改 Content-Type 行将编码更改为 UTF-8:

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

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

另外,我发现使用 rewind() 而不是 fseek() 更优雅:

rewind($f);

Thanks for your solution!

感谢您的解决方案!

回答by Indrajeet Singh

Try... csv download.

尝试... csv 下载。

<?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();
?>

回答by Sajidur Rahman

That is the function that 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();
}

回答by Kiran Reddy

Use the below code to convert a php array to CSV

使用以下代码将 php 数组转换为 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);

回答by half-fast

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.

然后,您将管理您的标题,就像 complex857 正在执行的操作一样吐出文件。如果您不再需要该文件,则可以使用unlink()删除该文件,或者如果您愿意,可以将其保留在服务器上。

回答by Ashwin Balani

Use the following,

使用以下,

echo "<script type='text/javascript'> window.location.href = '$file_name'; </script>";