逗号分隔文值

CSV 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号)。

CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。

范例

1. 下载文件

header('Content-Type: application/vnd.ms-excel;charset=utf-8');   
header("Content-Disposition: attachment; filename=test.csv");   
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');   
header('Expires:0');   
header('Pragma:public');


2. 写入文件

// write file
$fp = fopen($filename, 'w+');
foreach ($dataList as $data) {
    fputcsv($fp,$data);
}
fclose($fp);


3. 读取文件

// read file
$file = fopen($filename,'r');
while(feof($file) == false){
    $data = fgetcsv($file);
    print_r($data);
}
fclose($file);

4. 综合

[运行代码]

$dataList = array(
    array(
        'George',
        18,
        'USA',
        rand(),
    ) ,
    array(
        'James',
        27,
        'UK',
        rand(),
    ) ,
    array(
        'Woo',
        23,
        'CN',
        rand(),
    ) ,
);
$filename = __DIR__ . '/test.csv';

// write file
$fp = fopen($filename, 'w+');
foreach ($dataList as $data) {
    fputcsv($fp,$data);
}
fclose($fp);
echo "<pre>";
// read file
$file = fopen($filename,'r');
while(feof($file) == false){
    $data = fgetcsv($file);
    print_r($data);
}
fclose($file);

[执行结果]

Array
(
    [0] => George
    [1] => 18
    [2] => USA
    [3] => 163941109
)
Array
(
    [0] => James
    [1] => 27
    [2] => UK
    [3] => 556228747
)
Array
(
    [0] => Woo
    [1] => 23
    [2] => CN
    [3] => 2063530084
)

配置文件