php导出数据到csv是一种很常见的功能,且csv相比于excel文件有其一定的优势,首先csv对数据的行数没有限制,但是excel对数据的行数有一定的限制,因此,csv文件对于导出大量的数据来说很方便。
在本教程中,您将学习如何将PHP数组数据导出到CSV文件。
要将数组转换为CSV文件,我们可以使用fputcsv()函数。fputcsv()函数用于将行格式设置为CSV(逗号分隔值)文件,并将其写入打开的文件中。必须读取的文件和字段作为参数发送到fputcsv()函数,如果成功,则返回写入字符串的长度,如果失败,则返回FALSE。
fputcsv()函数将一行格式设置为CSV并将其写入打开的文件。
句法
fputcsv(file, fields, separator, enclosure, escape)
参数值
| 范围 | 描述 |
|---|---|
| 文件 | 必需的。指定要写入的打开文件 |
| 领域 | 必需的。指定从哪个数组获取数据 |
| 分隔器 | 可选的。指定字段分隔符的字符。默认为逗号(,) |
| 外壳 | 可选的。一个字符,用于指定现场附件字符。默认值为“ |
| 逃脱 | 可选的。指定转义字符。默认值为“ \\”。也可以是一个空字符串(“”),以禁用转义机制 |
例子:
-
- $data = array (
- array('header 1', 'header 2', 'header 3', 'header 4'),
- array('5656', '454545', '5455', '5454'),
- array('541212', '454545', '5455', '5454'),
- array('541212', '454545', '5455', '5454'),
- );
-
- $f = fopen('mycsv.csv', 'a'); // Configure fOpen to create, open and write only.
-
- // Loop over the array and passing in the values only.
- foreach ($data as $row)
- {
- fputcsv($f, $row);
- }
- // Close the file.
- fclose($f);
- ?>
代码明细–
fopen() 函数打开文件并对其进行写入。这使用两个参数
fopen 创建(如果不存在),并指示我们只想编写。fputcsv() 传递每个值。如何你想直接将数组输出到浏览器进行下载保存,可以使用下面的方法。
- // output headers so that the file is downloaded rather than displayed
- header('Content-type: text/csv');
- header('Content-Disposition: attachment; filename="demo.csv"');
-
- // do not cache the file
- header('Pragma: no-cache');
- header('Expires: 0');
-
- // create a file pointer connected to the output stream
- $file = fopen('php://output', 'w');
-
- // send the column headers
- fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
-
- // Sample data. This can be fetched from mysql too
- $data = array(
- array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
- array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
- array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
- array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
- array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
- );
-
- // output each row of the data
- foreach ($data as $row)
- {
- fputcsv($file, $row);
- }
-
- exit();
由于我们要下载文件,因此我们必须发送一些头信息(第2行和第3行)以告知浏览器下载文件。
以上是本文的全部类容,感谢阅读,希望能帮到大家。更多教程请访问码农之家