Read All New-line Delimited Records From a File Php

Read Time: 6 mins Languages:

In this post, I'll prove you how to use PHP'due south built-in functions to read and print the contents of a CSV file and convert it into an array. We'll utilize fopen() and fgetcsv() to read the contents of a CSV file, and so we'll catechumen 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 affair. In fact, it's one of the well-nigh common ways of storing data due to its simplicity—CSV files are piece of cake 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 await like this:

This information represents information about three people, with columns respective to their names, age, and chore. Although it's a unproblematic data format, it tin can exist tricky to read and eat.

Therefore, in this article, I will teach you how to open up 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 assortment using the array_map() function.

Of course, there are a number of tertiary-party packages we could use to achieve this, just PHP has built-in native functions that work slap-up.

Prerequisites

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

  • PHP version 5.6 or to a higher place installed on your machine
  • a development environment for PHP—either XAMPP or WampServer work well
  • some bones understanding of PHP concepts

Let'southward brainstorm!

Displaying a CSV File as a Table

In this section of the commodity, we will be reading a simple CSV file that contains a few words separated past the comma delimiter. For a start, nosotros volition use the simple file we used to a higher place, and then afterward we tin can proceed to using a random larger file. Of course, you can create your own file using Microsoft Excel or a text editor and salvage it with the CSV extension.

To read the file, we get-go have to discover it in the folder or location it is saved in. For easier access, you may desire to save it in the same folder where you have your program file. Then nosotros tin apply the fopen() function to read the file.

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

Now allow'due south get applied.

Create a file named csvtable.php somewhere it can exist 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 aforementioned folder every bit 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, information technology will render FALSE. Therefore, nosotros check that the file handle is not Fake before continuing to read the file.

The fgetcsv() file and so fetches CSV fields from the opened file, one line at a time. We tell fgetcsv to read at nigh 100 characters per line, and to use the comma separator as its delimiter. The words plant 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 file output of read.php file output of read.php file

The kickoff 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 Assortment

Now, there'due south more than i way to produce the array. We tin use the fgetcsv() function to automatically convert the contents of the CSV file into an array, or nosotros can use array_map.

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

This is similar to the instance in a higher place, where we used fgetcsv() to render a CSV file as an HTML table. Allow'due south see this in action. Create a PHP file with the post-obit contents:

In the above code, we created a function to read a CSV file and convert information technology to an array. Nosotros pass in a parameter with the CSV document file proper noun and path.

And then, we employ the feof() function to check whether the terminate 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 case above.

The parsed CSV fields from the CSV file are converted into an array using the fgetcsv() role and are appended ane at a fourth dimension to the $lines[] variable.

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

We then call the readDocument office, which passes the CSV document equally a parameter, and next, the contents of the CSV file are displayed equally beneath:

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

Using array_map() to Read a CSV File

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

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

Here is how we can utilize array_map and str_getcsv to map our CSV information into an assortment:

The higher up lawmaking 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 information for the entire file in $csv. The str_getcsv() role parses the CSV field contents of each line into an array.

The output of the above code snippet volition be the same equally above.

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

Conclusion

In this article, y'all learned how to handle a CSV file in PHP past reading and displaying its contents using PHP native functions similar fopen() and fgetcsv() and converting the CSV fields into an array. I showed you two means to practise this.

At present, try doing it yourself. Happy coding!

sinclairmuchey.blogspot.com

Source: https://code.tutsplus.com/articles/read-a-csv-to-array-in-php--cms-39471

0 Response to "Read All New-line Delimited Records From a File Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel