Import and export csv files in php

1. Import csv file

1. Create an import page

 

<!DOCTYPE html>
<html lang="zh-CN">
<meta charset="UTF-8">
<head>
    <title>文件提交表单</title>
</head>
<body>
<form action="test5.php" method="post" enctype="multipart/form-data">
    <label for="file">选择文件:</label>
    <input type="file" name="file" id="file">
    <input type="submit" name="submit" value="导入">
</form>
</body>
</html>

2. Import backend processing test5.php

<?php
/**
 * $filename 文件
 * $lineOne 是否显示标题
*/
function parseFile($filename,$lineOne=false) {
    if (!$filename) {
        die("未选择文件");
    }
    $file = fopen($filename, 'r');
    $arr = [];
    $i=0;
    while ($line = fgets($file)) {
        $i++;
        if($i==1&&!$lineOne){
           continue;
        }
        $line = rtrim($line, "\n\r\0");
        $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
        if ($encoding != 'utf-8') {
            $line = mb_convert_encoding($line, 'utf-8', $encoding);
        }

        $arr[] = explode(',', $line);

    }
    return $arr;
}
$filename = $_FILES['file']['tmp_name'];
$result = parseFile($filename);
print_r($result);

 

2. Export csv file

<?php
 
$output = fopen('php://output', 'w');
header('Content-type: application/csv;');
header('Content-Disposition: attachment; filename="测试——' . date("YmdHis", time()) . ".csv");
 
fputcsv($output, [
        iconv('UTF-8', 'GB2312', "标题"),
        iconv('UTF-8', 'GB2312', '哈哈'),
    ]
);
 
 
fputcsv($output, [
 
 
        iconv('UTF-8', 'GB2312', "名称"),
        iconv('UTF-8', 'GB2312', "年龄"),
        iconv('UTF-8', 'GB2312', "生日"),
    ]
 
);
$data=[
    ["name"=>'小明','age'=>'22','date'=>'1994-01-12'],
    ["name"=>'小a','age'=>'12','date'=>'1994-01-33'],
    ["name"=>'小b','age'=>'33','date'=>'1994-01-22'],
    ["name"=>'小c','age'=>'21','date'=>'1994-01-22'],
    ["name"=>'小d','age'=>'11','date'=>'1994-01-12'],
    ["name"=>'小e','age'=>'22','date'=>'1994-01-12'],
    ["name"=>'小e','age'=>'33','date'=>'1994-01-01'],
];
 
foreach ($data as $value){
 
 
    fputcsv($output, array(
            iconv('UTF-8', 'GB2312', $value['name']),
            "\t" . $value['age'],
            "\t" . $value['date'],
        )
    );
}

 

Guess you like

Origin blog.csdn.net/weixin_39934453/article/details/133207072