我是一名新手程序员,我搜索了很多有关我的问题的信息,但找不到有关此问题的有用解决方案或教程。
我的目标是我有一个 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: text/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);
}
}
这是我在项目中使用的函数,它按预期工作。
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();
}
我没有足够的声誉来回复@complex857解决方案。它效果很好,但我必须添加;在 Content-Disposition 标头的末尾。如果没有它,浏览器会在文件名末尾添加两个破折号(例如,文件将保存为“export.csv--”,而不是“export.csv”)。可能它试图消毒 在标题行的末尾。
正确的线条应该是这样的:
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();
?>
使用下面的代码将 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() 删除该文件,或者如果您愿意,也可以将其保留在服务器上。
更新@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);
}
}
代码可能有点难看,但它确实有效!
这个函数可以生成一个可下载的CSV文件,你可以设置名称和分隔符,无需繁琐的函数(标头函数中的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);
}
/**
* array_to_csv_download
*
*/
function array_to_csv_download($array, $filename = "export.csv", $delimiter = ",")
{
header('Content-Type: application/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// clean output buffer
ob_end_clean();
$handle = fopen('php://output', 'w');
// Write utf-8 bom to the file
fputs($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));
// 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();
}