PHP读取和写入CSV文件的代码写

发布时间:2023-04-15 16:30:02 作者:iii
来源:亿速云 阅读:95

这篇文章主要介绍“PHP读取和写入CSV文件的代码写”,在日常操作中,相信很多人在PHP读取和写入CSV文件的代码写问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”PHP读取和写入CSV文件的代码写”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1. 什么是 CSV 文件

CSV(逗号分隔值)文件是使用逗号分隔信息的文本文件。该文件的每一行都是一条数据记录,也就意味着它可以用于以表格的形式展现信息。

2. 从 CSV 文件中读取数据

我将使用内置函数 file 从 CSV 文件中读取数据,然后使用 str_getcsv() 解析包含逗号的字符串。

在介绍如何使用str_getcsv() 函数之前,我想向你介绍如何输出 CSV 文件中的数据。

<?php
    if($_FILES){
        var_dump(file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    }
?>

<html>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <button>upload</button>
        </form>
    </body>
</html>

当我使用上面的代码上传文件时,输出以下数据:

PHP读取和写入CSV文件的代码写

如图所示,每个字符串中都有逗号,每个逗号将一条信息与另一条信息隔开。

使用 array_map() 函数,并且 str_getcsv() 作为回调函数,该回调将解析每个具有逗号的字符串并将它们分隔在一个数组中。

if($_FILES){
    //loop through the csv file into an array
    $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    //dump result
    var_dump($theCSV);
}

输出如下:

PHP读取和写入CSV文件的代码写

输出的数据看起来比之前要好得多,我们将列标题(全名、QQ、电子邮件)作为该数组的第一个元素。

我们使用 array_walk() 函数遍历此数组 ,然后提供一个回调函数,它将列标题(全名、QQ、电子邮件)和每个 CSV 数据组合为一个新数组。

if($_FILES){
    //loop through the csv file into an array
    $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/
    array_walk($theCSV, function(&$ary) use($theCSV) {
        $ary = array_combine($theCSV[0], $ary);
    });
    //dump result
    var_dump($theCSV);
}
?>

注意,在上面的回调函数中,我使用了变量& 运算符将 $ary 通过引用传递给函数,这使的我们可以修改原始数组。当我们运行上面的代码时,这就是我们的 CSV 数组现在的样子:

PHP读取和写入CSV文件的代码写

注意这里有个问题:这个新数组的第一个元素是表头,因为我们之前让它与 CSV 数组的其他数组组装在了一起。可以使用 array_shift() 来解决这个问题。

if($_FILES){
    //loop through the csv file into an array
    $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/
    array_walk($theCSV, function(&$ary) use($theCSV) {
        $ary = array_combine($theCSV[0], $ary);
    });
    //remove column headers which is the first element
    array_shift($theCSV);
    //dump result
    var_dump($theCSV);
}

这就是我们最终的 CSV 数组的样子

PHP读取和写入CSV文件的代码写

将上面的代码封装成一个函数,如下:

function readCSV($file){
    if(empty($file) || !file_exists($file)) return;
    //store the column headers
    $headers = null;
    $theCSV = array_map('str_getcsv', file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/
    array_walk($theCSV, function(&$ary) use($theCSV, &$headers) {
            $ary = array_combine($theCSV[0], $ary);
            //store the headers
            $headers = $theCSV[0];
    });
    //remove column headers which is the first element of our csv array
    array_shift($theCSV);
    //return data
    return array(
        "headers" => $headers,
        "data" => $theCSV
    );
}

3. 将数据写入 CSV 文件

将数据写入 CSV 文件,其逻辑是使用 fopen() 函数以附加模式打开 CSV 文件, 然后用 fputcsv() 解析我们要写入 CSV 文件的数据,然后此方法将这些数据写入文件流当中。

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $file = "./my_csv_file.csv";
    //loop through the csv file into an array
    $csvData = readCSV($file);
    //create array to store the new data
    $newData = [];
    //loop through headers and then add values as a new array
    foreach($csvData['headers'] as $index => $key){
        if($key == 'Full Name'){
            $newData[$key] = $_POST['full_name'];
        }elseif($key == 'Email'){
            $newData[$key] = $_POST['email'];
        }elseif($key == 'Phone'){
            $newData[$key] = $_POST['phone'];
        }else{
            $newData[$key] = '';
        }
    }
    var_dump($newData);
}

如图所示就是我们将写入到 CSV 文件的数组的数据

PHP读取和写入CSV文件的代码写

在我们将这些数据写入到 CSV 文件之前,我们必须去掉 key,我们可以使用 array_values() 函数

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $file = "./my_csv_file.csv";
    //loop through the csv file into an array
    $csvData = readCSV($file);
    //create array to store the new data
    $newData = [];
    //loop through headers and then add values as a new array
    foreach($csvData['headers'] as $index => $key){
        if($key == 'Full Name'){
            $newData[$key] = $_POST['full_name'];
        }elseif($key == 'Email'){
            $newData[$key] = $_POST['email'];
        }elseif($key == 'Phone'){
            $newData[$key] = $_POST['phone'];
        }else{
            $newData[$key] = '';
        }
    }
    //open the csv file as in append mode
    $fp = fopen($file, 'a+');
    //remove keys from new data
    $newData = array_values($newData);
    //append data to csv file
    fputcsv($f, $newData);
    //close the resource
    fclose($fp);
}

不出意外的话,数据就会成功写入到 CSV 文件当中去了。

PHP读取和写入CSV文件的代码写

到此,关于“PHP读取和写入CSV文件的代码写”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. php语言中json实现的示例分析
  2. php中json_decode()的常见错误有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php csv

上一篇:Python基于pywinauto怎么实现自动化采集任务

下一篇:vue中怎么携带参数跳转页面

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》