Home>Article>Backend Development> How to read CSV content and store it in an array in PHP

How to read CSV content and store it in an array in PHP

青灯夜游
青灯夜游 forward
2022-02-25 16:20:40 7670browse

How to usePHPto read CSV into an array? The following article will show you how to use PHP to read CSV content and convert it into an array. I hope it will be helpful to you.

How to read CSV content and store it in an array in PHP

In this article, I will show you how to use PHP’s built-in functions to read and print the contents of a CSV file and convert it into an array . We will usefopen()andfgetcsv()to read the contents of the CSV file, and then usearray_map()andstr_getcsv()function to convert it into an array.

Introduction

Storing data files in comma-separated value (CSV) format is nothing new. In fact, it's one of the most common ways to store data due to its simplicity - CSV files are easy to read and write, and can be opened in a basic text editor. This type of file stores tabular data in plain text.

An example of such a file is this.

Elias,40,nurse Rehema,15,programmer Beatrice,23,doctor

This data represents information about three people, with columns corresponding to their names, ages, and jobs. Although this is a simple data format, it is tricky to read and consume.

So, in this article, I will teach you how to open a CSV file using PHP’s native functions (such asfopen()) and how to usefgetcsv()Method to read the contents of this file, and finally how to use thearray_map()function to convert this CSV file into an array.

Of course, we can use some third-party software packages to achieve these, but PHP's built-in local functions are very easy to use.

Prerequisites

To continue studying this article, you need the following conditions.

  • Have PHP 5.6 or higher installed on your machine
  • A PHP development environment--XAMPPorWampServerEverything is easy to use
  • Some basic understanding of PHP concepts

Let’s get started!

Display the CSV file as a table

In this part of the article, we will read a simple CSV file containing several words separated by commas. To start, we will use the simple file above, and later we can continue using a random large file. Of course, you can create your own file using Microsoft Excel or a text editor and save it with a CSV extension.

To read the file, we first need to find it in the folder or location where it is saved. For easier access, you may want to save it in the same folder as your program files. We can then use thefopen()function to read the file.

Afterwards, thefgetcsv()function checks the CSV field from the parsed line of the open file. This function takes three parameters: the file handle returned fromfopen(), the maximum length of lines to read, and a special delimiter - we call it the "delimiter". This can be a comma, a semicolon, or any other delimiter.

Now let’s do it in practice.

Create a file namedcsvtable.phpsomewhere that can be served with WAMP or XAMPP and copy the following code.

\n"; while(($data = fgetcsv($file_to_read, 100, ',')) !== FALSE){ echo ""; for($i = 0; $i < count($data); $i++) { echo "".$data[$i].""; } echo "\n"; } echo "\n"; fclose($file_to_read); } ?>

In this file, we first open thedata.csvfile, which should contain some comma separated data.fopenwill look for this file in the same folder ascsvtable.php. The'r'parameter tellsfopento open the file in read-only mode.

If the file is successfully opened,fopenwill return a file handle that can be used for reading operations on other files. Otherwise, it returnsFALSE. Therefore, before continuing to read the file, we check if the file handle isFALSE.

Then,fgetcsv()file gets the CSV fields from the open file, one line at a time. We tellfgetcsvto read up to 100 characters per line and use comma delimiters as delimiters. The words found in the file are then looped through and printed into an HTML table.

The last function isfclose(), which closes the open file. This will free up the memory used by the open file and allow other processes to access the file.

Opencsvtable**.php** via WAMP or XAMPP localhost server, or runphp read.phpfrom the command line, you can see the following output.

How to read CSV content and store it in an array in PHP

The first part of what we need to implement is done!

Now we will jump to converting the raw CSV fields into an array.

将原始CSV文件转换为数组

现在,有不止一种方法来产生数组。我们可以使用fgetcsv()函数将CSV文件的内容自动转换为数组,或者我们可以使用array_map

使用fgetcsv(),将CSV文件转换成数组

这与上面的例子类似,我们使用fgetcsv(),将一个CSV文件渲染成一个HTML表格。让我们来看看这个动作。创建一个具有以下内容的PHP文件。

'; print_r($csv); echo '
'; ?>

在上面的代码中,我们创建了一个函数来读取一个CSV文件并将其转换为数组。我们传入一个参数,包含CSV文件的名称和路径。

然后,我们使用feof()函数来检查是否已经到达文件的末端。在到达之前,我们需要使用fgetcsv()函数解析CSV字段,就像我们在上面的例子中做的那样。

使用fgetcsv()函数将CSV文件中被解析的CSV字段转换为数组,并将其逐一追加到$lines[]变量中。

最后,别忘了在退出函数之前,使用fclose()函数关闭已打开的文件。

然后,我们调用readDocument函数,该函数将CSV文件作为参数传递,接下来,CSV文件的内容将显示如下。

How to read CSV content and store it in an array in PHP

使用array_map()读取一个CSV文件

另外,你也可以使用array_map()函数将一个CSV文件读入一个数组。要做到这一点,你要使用str_getcsv作为回调函数。这是一个内置的PHP函数,用来解析一个CSV字符串到一个数组中。

回调函数是一些可执行的代码,它作为一个参数传递给另一段代码。这个参数预计在以后会被传递给它的代码回调。

下面是我们如何使用array_mapstr_getcsv,将我们的CSV数据映射成一个数组。

'; print_r($csv); echo '
'; ?>

上面的代码使用file()方法将CSV文件读成一个行数组。然后,通过数组映射,它在每一行上调用str_getcsv(),并将整个文件的数据存储在$csvstr_getcsv()函数将每一行的CSV字段内容解析为一个数组。

上述代码片断的输出将与上述相同。

注意到在直接使用file()array_map()函数时,需要的代码少了很多吗?

总结

在这篇文章中,你学到了如何在PHP中处理一个CSV文件,通过使用PHP本地函数如fopen()fgetcsv()读取和显示其内容,并将CSV字段转换为数组。我向你展示了两种方法。

现在,试着自己做吧。编码愉快!

相关文章推荐:php文件操作系列大汇总(持续更新~)

推荐学习:《PHP视频教程》、《PHP ARRAY

The above is the detailed content of How to read CSV content and store it in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete