将Array转换为csv php

时间:2016-03-11 11:35:20

标签: php arrays csv

我有一个这样的数组:

Array
(
    [0] => Array
        (
            [0] => Title
            [1] => Date
            [2] =>  Text
            [3] =>  Category
            [4] => ID
            [5] => img

        )

    [1] => Array
        (
            [0] => title 1
            [1] => 2005-11-20
            [2] => "Text article"
            [3] => News
            [4] => 100
            [5] => <img scr="">
        )

    [2] => Array
        (
           [0] => title 2
            [1] => 2005-11-21
            [2] => "Text article"
            [3] => News
            [4] => 101
            [5] => <img scr="">
        )

    [3] => Array
        (
            [0] => title 3
            [1] => 2005-11-22
            [2] => "Text article"
            [3] => News
            [4] => 102
            [5] => <img scr="">

}}

如何将其转换为CSV文件?

4 个答案:

答案 0 :(得分:5)

您应该使用fputcsv()功能。

  

fputcsv - 将行格式化为CSV并写入文件指针

以下示例在链接中给出。

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

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

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

fclose($fp);

答案 1 :(得分:2)

这就是你的方式

<?php

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

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

fclose($fp);
?>

答案 2 :(得分:2)

您可以使用此php函数fputcsv()

答案 3 :(得分:1)

是的,你可以。您将需要fputcsv()功能才能实现此目的。