[英]Creating csv file with php
I want to create a csv file, but when I run the code, it returns a blank page and no csv file.我想创建一个 csv 文件,但是当我运行代码时,它返回一个空白页并且没有 csv 文件。 I use PHP 5. I use the following code:
我使用 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);
?>
Thank you!谢谢!
Its blank because you are writing to file
.它是空白的,因为您正在写入
file
。 you should write to output
using php://output
instead and also send header information to indicate that it's csv.您应该改用
php://output
写入output
,并发送标头信息以指示它是 csv。
Example例子
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);
@Baba's answer is great. @Baba 的回答很棒。 But you don't need to use
explode
because fputcsv
takes an array as a parameter但是您不需要使用
explode
因为fputcsv
将数组作为参数
For instance, if you have a three columns, four lines document, here's a more straight version:例如,如果您有一个三列四行的文档,这里有一个更直接的版本:
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);
In case someone is still looking for an answer (a simple one), here is the simple way of creating a csv with PHP.如果有人仍在寻找答案(一个简单的答案),这里是使用 PHP 创建 csv 的简单方法。
//Let's say you want your csv file to have something like this:
**Title 1** | **Title 2** | **Title 3**
Value 1 | Value 2 | Value 3
Value 4 | Value 5 | Value 6
//create a variable and add your data to it
$data = "TITLE 1, TITLE 2, TITLE 3 \n";
$data .= val1 .",". val2 .",". val3 \n ;
$data .= val3 .",". val4 .",". val5 \n ;
//you can use a loop to add dynamic data to this variable, if you want.
//give your file a name.
$fileName = 'myData.csv';
//add the file path where you want to store your csv file
//you can use **$_SERVER['DOCUMENT_ROOT']** in your file path. Avoid using absoultue paths like **../** this
$filePath = 'your_path_to' . $fileName;
$fp = fopen($filePath, 'w+');
fwrite($fp, print_r($data, true));
//Once the data is written, it will be saved in the path given.
fclose($fp);
Just in case if someone is wondering to save the CSV file to a specific path for email attachments.以防万一有人想将 CSV 文件保存到电子邮件附件的特定路径。 Then it can be done as follows
然后可以如下进行
I know I have added a lot of comments just for newbies :)
我知道我已经为新手添加了很多评论:)
I have added an example so that you can summarize well.我添加了一个示例,以便您可以很好地总结。
$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 */
NOTE: The following is a very bad idea to increase the memory_limit and time limit , but I have only added to make sure if anyone faces the problem of connection time out or any other.
注意:以下是增加memory_limit和time limit 的一个非常糟糕的主意,但我只是添加以确保是否有人面临连接超时或任何其他问题。 Make sure to find out some alternative before sticking to it.
确保在坚持之前找到一些替代方案。
You have to add the following at the start of the above script.您必须在上述脚本的开头添加以下内容。
ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');
I think this is the shortest way我认为这是最短路线
$columns = [
'id',
'product_name',
'product_url',
'price',
'category'
];
$products = [
[1, 'product 1', 'https://example.com/product-1', '9.99', 'category 1'],
[2, 'product 2', 'https://example.com/product-2', '19.99', 'category 2'],
[3, 'product 3', 'https://example.com/product-3', '29.99', 'category 3'],
[4, 'product 4', 'https://example.com/product-4', '39.99', 'category 4'],
];
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="products.csv"');
echo implode(',', $columns) . PHP_EOL;
foreach ($products as $product){
echo implode(',', $product) . PHP_EOL;
}
i hope the example will be useful for you 我希望这个例子对你有用
$data= "Sr. No.,Vendor Name,Cargo Type,Amount,Delivery Address,Pickup Time,Delivery Time\n";
$i = 1;
if(!empty($detail)) {
foreach ($detail as $list) {
$data .= $i.",";
$data .= any data
$data .= any data
$data .= any data
$data .= any data
$data .= any data
$data .= any data
$data .="\n";
$i++;
}
}
header("Content-Type: application/csv");
$csv_filename = 'anyfilename.xlsx';
header("Content-Disposition:attachment;filename=".$csv_filename);
$fd = fopen ($csv_filename, "wb");
fputs($fd,$data);
fclose($fd);
echo $data;
die();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.