用php创建csv文件
Posted
技术标签:
【中文标题】用php创建csv文件【英文标题】:Creating csv file with php 【发布时间】:2013-03-08 05:51:09 【问题描述】:我想创建一个 csv 文件,但是当我运行代码时,它返回一个空白页并且没有 csv 文件。我使用 php 5。 我使用以下代码:
<?php
$data = array ('aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('data.csv', 'w');
foreach($data as $line)
$val = explode(",",$line);
fputcsv($fp, $val);
fclose($fp);
?>
谢谢!
【问题讨论】:
你需要echo
fclose($fp);
之后的输出
您不是echoing
任何东西,因此该页面将仅为空白。它只会根据您的代码为您创建 csv。
【参考方案1】:
它是空白的,因为您正在写信给file
。您应该改用php://output
写信给output
,并发送标头信息以表明它是csv。
例子
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'wb');
foreach ( $data as $line )
$val = explode(",", $line);
fputcsv($fp, $val);
fclose($fp);
【讨论】:
我能知道如何为此提供现有的 excel 工作表路径吗? @Howdy_McGee 是的,当然,您不能在输出已经发送后设置标题。您必须设置标题,然后发送输出。【参考方案2】:@Baba 的回答很棒。但是您不需要使用explode
,因为fputcsv
将数组作为参数
例如,如果您有一个三列四行的文档,这里有一个更直接的版本:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$user_CSV[0] = array('first_name', 'last_name', 'age');
// very simple to increment with i++ if looping through a database result
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);
$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line)
// though CSV stands for "comma separated value"
// in many countries (including France) separator is ";"
fputcsv($fp, $line, ',');
fclose($fp);
【讨论】:
当然,这应该有效,甚至可能更合适。更多详情here【参考方案3】:以防万一有人想将 CSV 文件保存到电子邮件附件的特定路径。那么就可以如下进行
我知道我已经为新手添加了很多 cmets :)
我加了一个例子,方便大家总结。
$activeUsers = /** Query to get the active users */
/** Following is the Variable to store the Users data as
CSV string with newline character delimiter,
its good idea of check the delimiter based on operating system */
$userCSVData = "Name,Email,CreatedAt\n";
/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user )
$userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
/** Here you can use with H:i:s too. But I really dont care of my old file */
$todayDate = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName = 'Active Users '.$todayDate.'.csv';
$filePath = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file
/** Just in case if I run the script multiple time
I want to remove the old file and add new file.
And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath))
unlink($filePath);
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);
/** Now you can send email with attachments from the $filePath */
注意:以下是增加 memory_limit 和 time limit,但我只是添加以确保是否有人面临连接超时或任何其他问题。 在坚持之前一定要找到一些替代方案。
您必须在上述脚本的开头添加以下内容。
ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');
【讨论】:
以上是关于用php创建csv文件的主要内容,如果未能解决你的问题,请参考以下文章
php读取csv文件时 用phpexcel很慢 用fgetcsv()函数中文乱码 请问还有啥excel库或函数方法来读csv文件吗