如何在Php中创建CSV下载

如何在Php中创建CSV下载,php,xml,csv,wordpress,fputcsv,Php,Xml,Csv,Wordpress,Fputcsv,我需要一些帮手。我使用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 = $xm

我需要一些帮手。我使用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下载。非常感谢您的帮助,但这是如何被标记为非主题的?

csv只是文本<代码>回显“{$first\u name},{$last\u name},{$company\u name}\n”
。繁荣即时CSV。现在,如果您想要有用的csv,请尝试
fputcsv()
@MarcB-不,它不是。它有各种转义规则用于处理包含特殊字符的数据。请参阅。此外,您还可以在输出数据之前添加描述列的标题。在这种情况下:
echo“firstname,lastname,company\u name\n”
$gmg\u data[]=array($first\u name,$last\u name,$company\u name)
<?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);
}
`$gmg_data[] = array($first_name, $last_name, $company_name);
$fp = fopen('php://output', 'w');
foreach($gmg_array as $row) {
fputcsv($fp, $row);
}`
<?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);
}