【问题标题】:How to create a CSV download in Php [closed]如何在 PHP 中创建 CSV 下载 [关闭]
【发布时间】:2014-12-31 12:59:59
【问题描述】:

我需要一些帮助。我正在使用 API 从 CRM 中提取数据,并且正在遍历每个变量,例如。 这是在 Wordpress 内部。下面的答案在隔离时确实可以正常工作。

for ($x = 0; $x<=$total_leads; $x++){
   $first_name = $xml->users->user[$x]->firstname;
   $last_name = $xml->users->user[$x]->lastname;
   $company_name = $xml->users->user[$x]->company;
}

我需要做的是将该数据推送到 .csv 文件中并下载。我在这里尝试了各种示例,但没有任何运气。看来数据必须存储在数组中。有什么建议吗?

更新:

`header('Content-Type: text/plain');
 header('Content-Disposition: attachment; filename=sample.csv');

for ($x = 0; $x<=$total_leads; $x++){
 $first_name = $xml->users->user[$x]->firstname;
 $last_name = $xml->users->user[$x]->lastname;
 $company_name = $xml->users->user[$x]->company;
 $gmg_data .= $first_name . ',' . $last_name . ',' . $company_name . '\n';

$fp = fopen('php://output', 'w');
foreach($gmg_array as $row) {
fputcsv($fp, $row);
}    
}`

仍然没有创建文件

更新:2014 年 11 月 4 日 - 上午 11:05

去掉最后几行代码并添加

`$gmg_data[] = array($first_name, $last_name, $company_name);
$fp = fopen('php://output', 'w');
foreach($gmg_array as $row) {
fputcsv($fp, $row);
}`

我仍然没有下载 .csv。感谢您提供的所有帮助,但如何将其标记为离题?

【问题讨论】:

  • csv 只是文本。 echo "{$first_name},{$last_name},{$company_name}\n"。繁荣。即时 CSV。现在,如果您想要有用的 csv,请尝试 fputcsv()
  • @MarcB — 不,不是。它有各种转义规则来处理带有特殊字符的数据。
  • 此外,您还可以在输出数据之前添加一个描述列的标题。在这种情况下:echo "firstname,lastname,company_name\n"
  • $gmg_data[] = array($first_name, $last_name, $company_name);

标签: php xml csv wordpress fputcsv


【解决方案1】:
<?php

// Represents the array you want to convert to a CSV
$data = array(
    array('a', 'b', 'c'),
    array('1', '2', '3'),
    array('4', '5', '6')
);

header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename=sample.csv');

$fp = fopen('php://output', 'w');

// This loops through the array, however if you are pulling the data row by 
// row from somewhere else then only the variable $row as an array is relevant
// in this example.
foreach($data as $row) {
    fputcsv($fp, $row);
}

【讨论】:

    猜你喜欢
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    相关资源
    最近更新 更多