通过php将数组插入csv

时间:2015-05-22 13:51:27

标签: php arrays csv

我有

Array
(
    [Name] => sdvsdv
    [CanaryAMS__Account_id__c] => abc
    [CanaryAMS__S3_File_Url__c] => ascfdsv
    [CanaryAMS__Description__c] => statement faxed to Aurelia at Occi 9/29/09
    [CanaryAMS__DocExternalId__c] => dscmdsv
)

我正在使用以下代码,但它提供了错误

<?php

$list = Array
(
    Name => sdvsdv
    CanaryAMS__Account_id__c => abc
    CanaryAMS__S3_File_Url__c => ascfdsv
    CanaryAMS__Description__c => statement faxed to Aurelia at Occi 9/29/09
    CanaryAMS__DocExternalId__c => dscmdsv
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

我想将此数据上传到csv文件中。名称下的sdvsdv,CanaryAMS__Account_id__c下的abc等等。

1 个答案:

答案 0 :(得分:1)

试试这个。有可能更好的方法,但这个简单的例子没有必要。

<?php

$list[0] = array
(
    'Name' => 'sdvsdv',
    'CanaryAMS__Account_id__c' => 'abc',
    'CanaryAMS__S3_File_Url__c' => 'ascfdsv',
    'CanaryAMS__Description__c' => 'statement faxed to Aurelia at Occi 9/29/09',
    'CanaryAMS__DocExternalId__c' => 'dscmdsv'
);
$list[1] = array
(
    'Name' => 'khk',
    'CanaryAMS__Account_id__c' => 'abckj',
    'CanaryAMS__S3_File_Url__c' => 'ghkghkv',
    'CanaryAMS__Description__c' => 'statement faxed to Aurelia at Occi 9/29/15',
    'CanaryAMS__DocExternalId__c' => 'dscmdsv'
);
$list[2] = array
(
    'Name' => 'gghfhfghf',
    'CanaryAMS__Account_id__c' => 'affbc',
    'CanaryAMS__S3_File_Url__c' => 'ascfffdsv',
    'CanaryAMS__Description__c' => 'statement faxed to Aurelia at Occi 05/05/20',
    'CanaryAMS__DocExternalId__c' => 'dscmdsv'
);

$header = '';
$fp = fopen('file.csv', 'w');
foreach ($list[0] as $k=>$v) $header .= $k.",";
$csvstring = trim($header,",")."\n";
fwrite($fp,$csvstring);
foreach ($list as $fields) fputcsv($fp, $fields);
fclose($fp);