使用php在本地计算机上保存csv文件

时间:2015-06-09 07:15:04

标签: php csv save

我有数组并使用它制作CSV,但不会在本地保存。

我应该在这里改变什么?

这是一个包含代码的数组。哪个无法在本地系统上创建CSV

$example_data = array(
  array('ID' => 1,'booktitle' => 'Quarter Share', 'author' => 'Nathan Lowell',
        'isbn' => '978-0982514542'),
  array('ID' => 2, 'booktitle' => '7th Son: Descent','author' => 'J. C. Hutchins',
        'isbn' => '0312384378'),
  array('ID' => 3, 'booktitle' => 'Shadowmagic', 'author' => 'John Lenahan',
        'isbn' => '978-1905548927'),
  array('ID' => 4, 'booktitle' => 'The Crown Conspiracy', 'author' => 'Michael J. Sullivan',
        'isbn' => '978-0979621130'),
  array('ID' => 5, 'booktitle' => 'Max Quick: The Pocket and the Pendant', 'author' => 'Mark Jeffrey',
        'isbn' => '978-0061988929'),
  array('ID' => 6, 'booktitle' => 'Jack Wakes Up: A Novel', 'author' => 'Seth Harwood',
        'isbn' => '978-0307454355')
);

function outputCsv($fileName, $assocDataArray)
{
    if(isset($assocDataArray['0'])){
        $fp = fopen('file.csv', 'w');
        fputcsv($fp, array_keys($assocDataArray['0']));
        foreach($assocDataArray AS $values){
            fputcsv($fp, $values);
            $data[]=$values;
        }

        $csv_handler = fopen ('file.csv','w');
        fwrite ($csv_handler,$data);
        fclose ($csv_handler);

        echo 'Data saved to csvfile.csv';

    }
}

2 个答案:

答案 0 :(得分:0)

我已经改变了你的一些功能并且正在为我工​​作:

function outputCsv($fileName, $assocDataArray)
{
    if(isset($assocDataArray['0'])){
        $fp = fopen($fileName, 'w');
        fputcsv($fp, array_keys($assocDataArray['0']));
        foreach($assocDataArray AS $values){
            fputcsv($fp, $values);
            $data[]=$values;
        }
/*
        $csv_handler = fopen ('file.csv','w');
        fwrite ($csv_handler,$data);
        fclose ($csv_handler);
*/
        fclose($fp); 
        echo 'Data saved to csvfile.csv';

    }
}

outputCsv('test.csv', $example_data);

您试图通过fwrite()函数编写数组类型数据,它只需要字符串。这就是它产生错误的原因。

答案 1 :(得分:0)

fwrite()函数没有直接将数组写入文件,你必须做这样的事情(我编辑了你的函数)

function outputCsv($fileName, $assocDataArray)
{
    if(isset($assocDataArray['0'])){
        $data = array();
        $fp = fopen('file.csv', 'w');
        fputcsv($fp, array_keys($assocDataArray['0']));
        foreach($assocDataArray AS $values){
            fputcsv($fp, $values);
            $data[]=$values;
        }

        $csv_handler = fopen ('file.csv','w');
        fwrite ($csv_handler, print_r($data, true));
        fclose ($csv_handler);

        echo 'Data saved to csvfile.csv';

    }
}