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

青灯夜游
Release: 2023-04-10 22:06:01
forward
7725 people have browsed it

How to use PHP to 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 use fopen() and fgetcsv() to read the contents of the CSV file, and then use array_map() and str_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
Copy after login

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 as fopen()) and how to use fgetcsv() Method to read the contents of this file, and finally how to use the array_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--XAMPP or WampServerEverything 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 the fopen() function to read the file.

Afterwards, the fgetcsv() function checks the CSV field from the parsed line of the open file. This function takes three parameters: the file handle returned from fopen(), 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 named csvtable.php somewhere that can be served with WAMP or XAMPP and copy the following code.

<?php

$file_to_read = fopen(&#39;data.csv&#39;, &#39;r&#39;);

if($file_to_read !== FALSE){
    
    echo "<table>\n";
    while(($data = fgetcsv($file_to_read, 100, &#39;,&#39;)) !== FALSE){
        echo "<tr>";
        for($i = 0; $i < count($data); $i++) {
            echo "<td>".$data[$i]."</td>";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";

    fclose($file_to_read);
}

?>
Copy after login

In this file, we first open the data.csv file, which should contain some comma separated data. fopen will look for this file in the same folder as csvtable.php. The 'r' parameter tells fopen to open the file in read-only mode.

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

Then, fgetcsv() file gets the CSV fields from the open file, one line at a time. We tell fgetcsv to 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 is fclose(), which closes the open file. This will free up the memory used by the open file and allow other processes to access the file.

Open csvtable**.php** via WAMP or XAMPP localhost server, or run php read.php from 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文件。

<?php
function csvToArray($csvFile){

    $file_to_read = fopen($csvFile, &#39;r&#39;);

    while (!feof($file_to_read) ) {
        $lines[] = fgetcsv($file_to_read, 1000, &#39;,&#39;);

    }

    fclose($file_to_read);
    return $lines;
}

//read the csv file into an array
$csvFile = &#39;data.csv&#39;;
$csv = csvToArray($csvFile);

//render the array with print_r
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($csv);
echo &#39;
Copy after login
'; ?>

在上面的代码中,我们创建了一个函数来读取一个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数据映射成一个数组。

<?php
$csv = array_map(&#39;str_getcsv&#39;, file(&#39;data.csv&#39;));
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($csv);
echo &#39;
Copy after login
'; ?>

上面的代码使用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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!