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'],
        )
    );
}
相关推荐
睡美人的小仙女1278 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo8 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk8 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
缺点内向9 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫9 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9969 小时前
Java 所有关键字及规范分类
java·开发语言
java1234_小锋9 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_9445255410 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
qq_4171292510 小时前
C++中的桥接模式变体
开发语言·c++·算法
开源技术10 小时前
如何将本地LLM模型与Ollama和Python集成
开发语言·python