In this article, I’ll show you how to use PHP’s built-in functions to read and print the contents of a CSV file and convert it to an array. We’ll read the contents of the CSV file using fopen() and fgetCSV (), and then convert it into an array using the array_map() and str_getCSV () functions.

Introduction to the

Storing data files in comma-separated value (CSV) format is nothing new. In fact, because of its simplicity, it is one of the most common ways to store data –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 would look like this.

Elias,40,nurse
Rehema,15,programmer
Beatrice,23,doctor
Copy the code

This data represents information for three people, with columns corresponding to their name, age, and job. Although this is a simple data format, it can be tricky to read and consume.

So, in this article, I’ll show you how to open a CSV file using PHP native functions such as fopen(), how to read the contents of the file using the fgetCSV () method, and finally how to convert the CSV file to an array using the array_map() function.

Of course, we can use some third-party packages to do this, but PHP’s built-in native functions are great.

The premise condition

To continue with this article, you need the following.

  • You have PHP 5.6 or higher installed on your machine
  • A PHP development environment –XAMPP or WampServer — works well
  • Some basic understanding of PHP concepts

Let’s get started!

Displays the CSV file as a table

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

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

After that, the fgetCSV () function checks the CSV field from the parsed line of the open file. This function takes three arguments: the handle to the file returned from fopen(), the maximum length of the line to read, and a special delimiter — we call it a “delimiter”. This can be a comma, a semicolon, or any other separator.

Now let’s put it into practice.

Create a file called csvtable.php where you can serve it 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); }? >Copy the code

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’ argument tells fopen to open the file in read-only mode.

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

The fgetCSV () file then retrieves the CSV fields from the open file, one line at a time. We tell fgetCSV to read a maximum of 100 characters per line and to use a comma separator as the separator. 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 frees up memory used by the open file and allows other processes to access it.

Open csvTable **.php** from the WAMP or XAMPP localhost server, or run PHP read.php from the command line, and you can see the following output.

The first part we need to implement is done!

Now, we’ll jump to converting the original CSV field into an array.

Convert the original CSV file to an array

Now, there’s more than one way to generate arrays. We can use the fgetcsv() function to automatically convert the contents of the CSV file into an array, or we can use array_map.

usefgetcsv()Convert the CSV file to an array

This is similar to the example above, where we use fgetcsv() to render a CSV file into an HTML table. Let’s take a look at this. Create a PHP file with the following contents.

<? 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>'; print_r($csv); echo '</pre>'; ? >Copy the code

In the code above, we created a function to read a CSV file and convert it to an array. We pass in a parameter containing the name and path of the CSV file.

We then use the feof() function to check if the end of the file has been reached. Before arriving, we need to parse the CSV field using the fgetCSV () function, as we did in the example above.

Use the fgetcsv() function to convert the parsed CSV fields in the CSV file into arrays and append them one by one to the $lines[] variable.

Finally, don’t forget to use the fclose() function to close the open file before exiting the function.

We then call the readDocument function, which passes the CSV file as an argument, and the contents of the CSV file are displayed as follows.

usearray_map()Read a CSV file

Alternatively, you can use the array_map() function to read a CSV file into an array. To do this, you use str_getCSV as the callback function. This is a built-in PHP function that parses a CSV string into an array.

Callbacks are executable code that is passed as an argument to another piece of code. This parameter is expected to be passed to its code callback later.

Here’s how we can map our CSV data into an array using array_map and str_getCSV.

<? php $csv = array_map('str_getcsv', file('data.csv')); echo '<pre>'; print_r($csv); echo '</pre>'; ? >Copy the code

The above code uses the file() method to read the CSV file as an array of lines. Then, through array mapping, it calls str_getCSV () on each line and stores the entire file’s data at $CSV. The str_getCSV () function parses the CSV field contents of each row into an array.

The output of the code snippet above will be the same as above.

Notice how much less code is required when using the file() and array_map() functions directly?

conclusion

In this article, you learned how to process a CSV file in PHP by reading and displaying its contents using PHP native functions such as fopen() and fgetCSV (), and converting CSV fields into arrays. I showed you two ways.

Now, try doing it yourself. Happy coding!