Php 简明教程

PHP – Handle CSV File

流行的电子表格程序使用 CSV 文件格式(代表以逗号分隔的值)来将工作表数据导出为纯文本。文件中的每一行代表工作表中的一行,每一列中的值都用逗号分隔。

Popular spreadsheet programs use the CSV file format (which stands for Comma Separated Values) to export worksheet data in plain text. Each line in the file represents one row of the worksheet, with values in each column separated by commas.

PHP 的文件系统函数库提供了两个函数 - fgetcsv()fputcsv() - 分别用来从 CSV 文件读取数据到一个数组中,并将数组元素放入 CSV 文件中。

PHP’s filesystem function library provides two functions – fgetcsv() and fputcsv() – respectively to read data from a CSV file into an array and put the array elements in a CSV file.

The fgetcsv() Function

getcsv() 函数从文件指针读取一行,并将其解析为 CSV 字段。

The getcsv() function reads the line from the file pointer, and parses it into CSV fields.

fgetcsv(
   resource $stream,
   ?int $length = null,
   string $separator = ",",
   string $enclosure = "\"",
   string $escape = "\\"
): array|false

$stream 参数是一个文件资源的句柄,在 read mode 中打开。用来解析字段的默认分隔符号是逗号,如果你需要,可以指定任何其他符号。

The $stream parameter is a handle to the file resource, opened in read mode. The default separator symbol to parse the fields is comma, you can specify any other symbol if required.

fgetcsv() 函数返回一个包含字段的索引数组。如果函数遇到任何错误,它会返回 false

The fgetcsv() function returns an indexed array containing the fields. If the function encounters any error, it returns false.

为了演示 fgetcsv() 函数的使用,将以下文本保存在当前工作目录中,作为“hello.txt”。

To demonstrate the use of fgetcsv() function, store the following text as "hello.txt" in the current working directory.

Name, Email, Post, Salary
Ravishankar, ravi@gmail.com, Manager, 40000
Kavita, kavita@hotmail.com, Assistant, 25000
Nandkumar, nandu@example.com, Programmer, 30000

Example

下面的 PHP 代码从这个文件读取 CSV 数据,并返回一个数组。然后在 HTML 表格中呈现数组中的字段 -

The following PHP code reads the CSV data from this file, and returns an array. The fields in the array are then rendered in a HTML table −

<?php
   $filename = 'hello.csv';
   $data = [];

   // open the file
   $f = fopen($filename, 'r');

   if ($f === false) {
      die('Cannot open the file ' . $filename);
   }

   // read each line in CSV file at a time
   while (($row = fgetcsv($f)) !== false) {
      $data[] = $row;
   }

   // close the file
   fclose($f);
   echo "<table border=1>";
   foreach ($data as $row) {
      echo "<tr>";
      foreach($row as $val) {
         echo "<td>$val</td>";
      }
      echo "</tr>";
   }
   echo "</table>";
?>

它将生成以下 output

It will produce the following output

Name

Email

Post

Salary

Ravishankar

ravi@gmail.com

Manager

40000

Kavita

kavita@hotmail.com

Assistant

25000

Nandkumar

nandu@example.com

Programmer

30000

The fputcsv() Function

fputcsv() 函数将一个索引数组及其元素(由逗号分隔)放入 CSV 文件当前文件指针的位置。

Te fputcsv() function puts an indexed array with its elements separated by commas, at the current file pointer position of a CSV file.

fputcsv(
   resource $stream,
   array $fields,
   string $separator = ",",
   string $enclosure = "\"",
   string $escape = "\\",
   string $eol = "\n"
): int|false

目标文件必须以写模式打开。第二个强制参数是一个包含由逗号分隔的字段的数组。就像在 fgetcsv() 函数中,默认分隔符号是逗号。

The target file must be opened in write mode. The second mandatory parameter is an array consisting of comma separated fields. As in case of fgetcsv() function, the default separator is comma.

Example

在下面的代码中,一个由逗号分隔的值组成的二维数组被写入一个 CSV 文件。

In the following code, a two dimensional array of comma separated values is written into a CSV file.

<?php
   $data = [
      ["Name", "Email", "Post", "Salary"],
      ["Ravishankar", "ravi@gmail.com", "Manager", "40000"],
      ["Kavita", "kavita@hotmail.com", "Assistant", "25000"],
      ["Nandkumar", "nandu@example.com", "Programmer", "30000"],
   ];
   $filename = 'employee.csv';

   // open csv file for writing
   $f = fopen($filename, 'w');

   if ($f === false) {
      die('Error opening the file ' . $filename);
   }

   // write each row at a time to a file
   foreach ($data as $row) {
      fputcsv($f, $row);
   }

   // close the file
   fclose($f);
?>

在上面程序执行之后,“employee.csv”文件应当被创建在当前工作目录中。

The "employee.csv" file should be created in the current working directory, after the above program is executed.