php之导入导出csv文件

一、导入csv文件

1、创建导入页面

html 复制代码
<!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、导入后端处理test5.php

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);

二、导出csv文件

php 复制代码
<?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'],
        )
    );
}
相关推荐
jimy127 分钟前
c++的 Type Traits (一)
开发语言·c++
我是唐青枫31 分钟前
Yii2 Applications 详解:应用生命周期、组件配置与多入口实战
php
Web极客码1 小时前
Python Ollama 本地 Agent 入门与订单查询实践
开发语言·jvm·python
kimnoic2 小时前
PHP 8.2的DNF类型怎么用才规范
开发语言·php
_Evan_Yao2 小时前
前后端联调怎么排查问题?从 Network 到后端日志,一步步定位错误
开发语言·后端·团队开发·需求分析
hudd6682 小时前
JavaEE 初阶 - 多线程(进阶)
java·开发语言·java-ee
小白快快跑哦2 小时前
python-字符串全解(六):正则表达式-前后相断言
开发语言·python·正则表达式·前后相断言
kimnoic2 小时前
Python数据分析中正则表达式匹配字符串与常用函数示例详解
开发语言·python
中屹指纹浏览器svip2 小时前
打开账号环境网页报错,常见原因有哪些?
服务器·开发语言·php·中屹指纹浏览器
朝朝辞暮i3 小时前
第 01 讲:Python 变量、对象、数据类型与内存引用
开发语言·python