PHP 中 CSV 文件的读取和写入

997 阅读2分钟

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>

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

image.png

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

使用 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);
}

输出如下:

csv_php_2

输出的数据看起来比之前要好得多,我们将列标题(全名、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 数组现在的样子:

csv_php_3

注意这里有个问题:这个新数组的第一个元素是表头,因为我们之前让它与 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 数组的样子

csv_php_4

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

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 文件的数组的数据

csv_php_5

在我们将这些数据写入到 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 文件当中去了。

image.png