Google+
Shineyrock web design & consultancy

Shineyrock

blog

  • like 4 25

    Read a CSV to an Array in PHP

    In this post, 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 into an array. We'll use fopen() and fgetcsv() to read the contents of a CSV file, and then we'll convert it into an array using the array_map() and str_getcsv() functions.

    Introduction

    Storing data files in comma-separated values (CSV) format is no new thing. In fact, it’s one of the most common ways of storing 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 the form of plain text.

    An example of such a file would look like this:

    This data represents information about three people, with columns corresponding to their names, age, and job. Although it's a simple data format, it can be tricky to read and consume.

    Therefore, in this article, I will teach you how to open CSV files using PHP's native functions like fopen(), how to read the contents of this file with the use of the fgetcsv() method, and lastly how to convert this CSV file into an array using the array_map() function.

    Of course, there are a number of third-party packages we could use to achieve this, but PHP has built-in native functions that work great. 

    Prerequisites

    To proceed with this article, you'll need the following:

    • PHP version 5.6 or above installed on your machine
    • a development environment for PHP—either XAMPP or WampServer work well
    • some basic understanding of PHP concepts

    Let’s begin!

    Displaying a CSV File as a Table

    In this section of the article, we will be reading a simple CSV file that contains a few words separated by the comma delimiter. For a start, we will use the simple file we used above, and then later we can proceed to using a random larger file. Of course, you can create your own file using Microsoft Excel or a text editor and save it with the CSV extension.

    To read the file, we first have to find it in the folder or location it is saved in. For easier access, you may want to save it in the same folder where you have your program file. Then we can use the fopen() function to read the file.

    Afterward, the fgetcsv() function checks for CSV fields from a parsed line of the open file. This function requires three parameters: the file handle returned from fopen(), the maximum length of the line to be read, and the special separator character—which we refer to as the "delimiter". This can be a comma, a semi-colon, or any other separator.

    Now let’s get practical.

    Create a file named csvtable.php somewhere it can be served with WAMP or XAMPP, and copy the following code.

    In this file, we're first opening 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 as read-only. 

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

    The fgetcsv() file then fetches CSV fields from the opened file, one line at a time. We tell fgetcsv to read at most 100 characters per line, and to use the comma separator as its delimiter. The words found in the file are then looped through and printed into an HTML table.

    The last function is the fclose() function, which closes the opened file. This releases the memory used by the open file and allows other processes to have access to the file.

    Open csvtable.php through the WAMP or XAMPP localhost server, or run php read.php from the command line to see the following output:

    output of read.php fileoutput of read.php fileoutput of read.php file

    The first part of what we needed to achieve is done already!

    Now, we’ll jump into converting the raw CSV fields into an array.

    Converting the Raw CSV File Into an Array

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

    Using fgetcsv() to Convert a CSV File Into an Array

    This is similar to the example above, where we used fgetcsv() to render a CSV file as an HTML table. Let’s see this in action. Create a PHP file with the following contents:

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

    Then, we use the feof() function to check whether the end of file has been reached. Until it has, we need to parse the CSV fields using the fgetcsv() function, just like we did in the example above.

    The parsed CSV fields from the CSV file are converted into an array using the fgetcsv() function and are appended one at a time to the $lines[] variable.

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

    We then call the readDocument function, which passes the CSV document as a parameter, and next, the contents of the CSV file are displayed as below:

    output of csv to array exampleoutput of csv to array exampleoutput of csv to array example

    Using array_map() to Read a CSV File

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

    A callback function is some executable code that is passed to another piece of code as an argument. This argument is expected to be called back later on by the code it is passed to.

    Here is how we can use array_map and str_getcsv to map our CSV data into an array:

    The above code uses the file() method to read the CSV file into an array of lines. Then, with array map, it calls str_getcsv() on each line and stores the data for the entire file in $csv. The str_getcsv() function parses the CSV field contents of each line into an array.

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

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

    Conclusion

    In this article, you learned how to handle a CSV file in PHP by reading and displaying its contents using PHP native functions like fopen() and fgetcsv() and converting the CSV fields into an array. I showed you two ways to do this. 

    Now, try doing it yourself. Happy coding!

    martijn broeders

    founder/ strategic creative bij shineyrock web design & consultancy
    e-mail: .(JavaScript must be enabled to view this email address)
    telefoon: 434 210 0245

Per - categorie

    Op - datum