翼度科技»论坛 编程开发 PHP 查看内容

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

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
1. 什么是 CSV 文件

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

2. 从 CSV 文件中读取数据

我将使用内置函数
  1. file
复制代码
从 CSV 文件中读取数据,然后使用
  1. str_getcsv()
复制代码
解析包含逗号的字符串。
在介绍如何使用
  1. str_getcsv()
复制代码
函数之前,我想向你介绍如何输出 CSV 文件中的数据。
  1. <?php
  2.     if($_FILES){
  3.         var_dump(file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
  4.     }
  5. ?>

  6. <html>
  7.     <body>
  8.         <form method="post" enctype="multipart/form-data">
  9.             <input type="file" name="file" />
  10.             <button>upload</button>
  11.         </form>
  12.     </body>
  13. </html>
复制代码
当我使用上面的代码上传文件时,输出以下数据:

如图所示,每个字符串中都有逗号,每个逗号将一条信息与另一条信息隔开。
使用
  1. array_map()
复制代码
函数,并且
  1. str_getcsv()
复制代码
作为回调函数,该回调将解析每个具有逗号的字符串并将它们分隔在一个数组中。
  1. if($_FILES){
  2.     //loop through the csv file into an array
  3.     $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
  4.     //dump result
  5.     var_dump($theCSV);
  6. }
复制代码
输出如下:

输出的数据看起来比之前要好得多,我们将列标题(全名、QQ、电子邮件)作为该数组的第一个元素。
我们使用
  1. array_walk()
复制代码
函数遍历此数组 ,然后提供一个回调函数,它将列标题(全名、QQ、电子邮件)和每个 CSV 数据组合为一个新数组。
  1. if($_FILES){
  2.     //loop through the csv file into an array
  3.     $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
  4.     /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/
  5.     array_walk($theCSV, function(&$ary) use($theCSV) {
  6.         $ary = array_combine($theCSV[0], $ary);
  7.     });
  8.     //dump result
  9.     var_dump($theCSV);
  10. }
  11. ?>
复制代码
注意,在上面的回调函数中,我使用了变量
  1. &
复制代码
运算符将
  1. $ary
复制代码
通过引用传递给函数,这使的我们可以修改原始数组。当我们运行上面的代码时,这就是我们的 CSV 数组现在的样子:

注意这里有个问题:这个新数组的第一个元素是表头,因为我们之前让它与 CSV 数组的其他数组组装在了一起。可以使用
  1. array_shift()
复制代码
来解决这个问题。
  1. 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 数组的样子

将上面的代码封装成一个函数,如下:
  1. 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 文件,其逻辑是使用
  1. fopen()
复制代码
函数以附加模式打开 CSV 文件, 然后用
  1. fputcsv()
复制代码
解析我们要写入 CSV 文件的数据,然后此方法将这些数据写入文件流当中。
  1. if($_SERVER['REQUEST_METHOD'] == "POST"){
  2.     $file = "./my_csv_file.csv";
  3.     //loop through the csv file into an array
  4.     $csvData = readCSV($file);
  5.     //create array to store the new data
  6.     $newData = [];
  7.     //loop through headers and then add values as a new array
  8.     foreach($csvData['headers'] as $index => $key){
  9.         if($key == 'Full Name'){
  10.             $newData[$key] = $_POST['full_name'];
  11.         }elseif($key == 'Email'){
  12.             $newData[$key] = $_POST['email'];
  13.         }elseif($key == 'Phone'){
  14.             $newData[$key] = $_POST['phone'];
  15.         }else{
  16.             $newData[$key] = '';
  17.         }
  18.     }
  19.     var_dump($newData);
  20. }
复制代码
如图所示就是我们将写入到 CSV 文件的数组的数据

在我们将这些数据写入到 CSV 文件之前,我们必须去掉 key,我们可以使用
  1. array_values()
复制代码
函数
  1. if($_SERVER['REQUEST_METHOD'] == "POST"){
  2.     $file = "./my_csv_file.csv";
  3.     //loop through the csv file into an array
  4.     $csvData = readCSV($file);
  5.     //create array to store the new data
  6.     $newData = [];
  7.     //loop through headers and then add values as a new array
  8.     foreach($csvData['headers'] as $index => $key){
  9.         if($key == 'Full Name'){
  10.             $newData[$key] = $_POST['full_name'];
  11.         }elseif($key == 'Email'){
  12.             $newData[$key] = $_POST['email'];
  13.         }elseif($key == 'Phone'){
  14.             $newData[$key] = $_POST['phone'];
  15.         }else{
  16.             $newData[$key] = '';
  17.         }
  18.     }
  19.     //open the csv file as in append mode
  20.     $fp = fopen($file, 'a+');
  21.     //remove keys from new data
  22.     $newData = array_values($newData);
  23.     //append data to csv file
  24.     fputcsv($f, $newData);
  25.     //close the resource
  26.     fclose($fp);
  27. }
复制代码
不出意外的话,数据就会成功写入到 CSV 文件当中去了。

以上就是PHP读取和写入CSV文件的示例代码的详细内容,更多关于PHP CSV文件的资料请关注脚本之家其它相关文章!

来源:https://www.jb51.net/article/281057.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具