繁体   English   中英

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

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

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

我的目标是我有一个 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.'";');

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

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

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

rewind($f);

感谢您的解决方案!

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

这是我用于我的项目的功能,它按预期工作。

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'] ) , $delimiter );

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

    fclose( $handle );

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

使用以下代码将 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);

如果你的数组结构总是以这种精确的方式是多维的,那么我们可以像这样迭代元素:

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

这是一种方法……您可以手动完成,但这种方法更快、更容易理解和阅读。

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

UTF-8 编码更新

更新@complex857 的答案

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

    // open the "output" stream
    $f = fopen('php://output', 'w');
    // Write utf-8 bom to the file
    fputs($f, chr(0xEF) . chr(0xBB) . chr(0xBF));

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

可能有点丑陋的代码,但它的工作原理!

这个 function 可以生成一个可下载的 CSV 文件,您可以设置名称和分隔符而无需棘手的功能(header 功能中的 UTF-8 编码)。

/**
 * Array2CSVDownload
 * 
 */
function Array2CSVDownload($array, $filename = "export.csv", $delimiter=";") {

    // force object to be array, sorry i was working with object items
    $keys = array_keys( (array) $array[0] );
    // use keys as column titles
    $data = [];
    array_push($data, implode($delimiter, $keys));
    // working with items
    foreach ($array as $item) {
        $values = array_values((array) $item);
        array_push($data, implode($delimiter, $values)); 
    }
    // flush buffer
    ob_flush();
    // mixing items
    $csvData = join("\n", $data);
    //setup headers to download the file
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    //setup utf8 encoding
    header('Content-Type: application/csv; charset=UTF-8');
    // showing the results
    die($csvData);

}   

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

我的目标是我有一个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] => 
        )

)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM