How to read CSV content and store it in an array in PHP
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.
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
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('data.csv', 'r'); if($file_to_read !== FALSE){ echo "<table>\n"; while(($data = fgetcsv($file_to_read, 100, ',')) !== 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); } ?>
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.
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, 'r'); while (!feof($file_to_read) ) { $lines[] = fgetcsv($file_to_read, 1000, ','); } fclose($file_to_read); return $lines; } //read the csv file into an array $csvFile = 'data.csv'; $csv = csvToArray($csvFile); //render the array with print_r echo '<pre class="brush:php;toolbar:false">'; print_r($csv); echo '
在上面的代码中,我们创建了一个函数来读取一个CSV文件并将其转换为数组。我们传入一个参数,包含CSV文件的名称和路径。
然后,我们使用feof()
函数来检查是否已经到达文件的末端。在到达之前,我们需要使用fgetcsv()
函数解析CSV字段,就像我们在上面的例子中做的那样。
使用fgetcsv()
函数将CSV文件中被解析的CSV字段转换为数组,并将其逐一追加到$lines[]
变量中。
最后,别忘了在退出函数之前,使用fclose()
函数关闭已打开的文件。
然后,我们调用readDocument
函数,该函数将CSV文件作为参数传递,接下来,CSV文件的内容将显示如下。
使用array_map()
读取一个CSV文件
另外,你也可以使用array_map()
函数将一个CSV文件读入一个数组。要做到这一点,你要使用str_getcsv
作为回调函数。这是一个内置的PHP函数,用来解析一个CSV字符串到一个数组中。
回调函数是一些可执行的代码,它作为一个参数传递给另一段代码。这个参数预计在以后会被传递给它的代码回调。
下面是我们如何使用array_map
和str_getcsv
,将我们的CSV数据映射成一个数组。
<?php $csv = array_map('str_getcsv', file('data.csv')); echo '<pre class="brush:php;toolbar:false">'; print_r($csv); echo '
上面的代码使用file()
方法将CSV文件读成一个行数组。然后,通过数组映射,它在每一行上调用str_getcsv()
,并将整个文件的数据存储在$csv
。str_getcsv()
函数将每一行的CSV字段内容解析为一个数组。
上述代码片断的输出将与上述相同。
注意到在直接使用file()
和array_map()
函数时,需要的代码少了很多吗?
总结
在这篇文章中,你学到了如何在PHP中处理一个CSV文件,通过使用PHP本地函数如fopen()
和fgetcsv()
读取和显示其内容,并将CSV字段转换为数组。我向你展示了两种方法。
现在,试着自己做吧。编码愉快!
相关文章推荐:php文件操作系列大汇总(持续更新~)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
