W3c Php Turn a Csv File to an Array Without Uploading File.
Read Time: 6 mins Languages:
In this post, I'll bear witness y'all how to use PHP's built-in functions to read and print the contents of a CSV file and convert it into an array. Nosotros'll use fopen() and fgetcsv() to read the contents of a CSV file, and then we'll catechumen it into an array using the array_map() and str_getcsv() functions.
Introduction
Storing information files in comma-separated values (CSV) format is no new affair. In fact, it'southward one of the near mutual means 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 information in the course of plain text.
An example of such a file would expect like this:
Elias,twoscore,nurse Rehema,15,programmer Beatrice,23,doctor
This data represents data about iii 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'due south 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() part.
Of class, there are a number of third-party packages we could employ to achieve this, just PHP has built-in native functions that work great.
Prerequisites
To proceed with this article, you lot'll need the following:
- PHP version v.six or above installed on your machine
- a development environs for PHP—either XAMPP or WampServer work well
- some basic understanding of PHP concepts
Allow's begin!
Displaying a CSV File as a Tabular array
In this section of the article, we will be reading a elementary CSV file that contains a few words separated by the comma delimiter. For a starting time, we will use the elementary file nosotros used to a higher place, and and so 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 get-go take to find it in the folder or location it is saved in. For easier access, y'all may want to save it in the same folder where y'all have your program file. Then nosotros can employ the fopen() function to read the file.
Afterward, the fgetcsv() function checks for CSV fields from a parsed line of the open up file. This office requires 3 parameters: the file handle returned from fopen(), the maximum length of the line to be read, and the special separator grapheme—which we refer to every bit the "delimiter". This tin can be a comma, a semi-colon, or whatever other separator.
Now let's get applied.
Create a file named csvtable.php somewhere it tin be served with WAMP or XAMPP, and re-create the following lawmaking.
<?php $file_to_read = fopen('information.csv', 'r'); if($file_to_read !== FALSE){ repeat "<table>\north"; while(($information = fgetcsv($file_to_read, 100, ',')) !== FALSE){ repeat "<tr>"; for($i = 0; $i < count($data); $i++) { echo "<td>".$data[$i]."</td>"; } echo "</tr>\n"; } repeat "</table>\n"; fclose($file_to_read); } ?> In this file, we're first opening the information.csv file, which should contain some comma-separated data. fopen volition look for this file in the same binder as csvtable.php. The 'r' parameter tells fopen to open the file every bit read-only.
If the file is opened successfully, fopen volition return a file handle which can be used for other file reading operations. Otherwise, it volition render Faux. Therefore, we check that the file handle is not False before continuing to read the file.
The fgetcsv() file and so fetches CSV fields from the opened file, ane line at a time. Nosotros tell fgetcsv to read at most 100 characters per line, and to utilize the comma separator as its delimiter. The words found in the file are then looped through and printed into an HTML table.
The last role is the fclose() function, which closes the opened file. This releases the memory used past 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 post-obit output:
The first part of what we needed to achieve is done already!
At present, nosotros'll spring into converting the raw CSV fields into an array.
Converting the Raw CSV File Into an Array
At present, there'due south more than than ane 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 apply 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 every bit an HTML table. Allow's run across this in activeness. Create a PHP file with the following contents:
<?php part 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 = 'information.csv'; $csv = csvToArray($csvFile); //render the assortment with print_r echo '<pre>'; print_r($csv); echo '</pre>'; ?> In the above code, we created a role to read a CSV file and convert it to an array. We laissez passer in a parameter with the CSV document file name and path.
So, we use the feof() function to check whether the stop of file has been reached. Until it has, we need to parse the CSV fields using the fgetcsv() function, only 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 part, which passes the CSV document as a parameter, and next, the contents of the CSV file are displayed as below:
Using array_map() to Read a CSV File
Alternatively, you tin use the array_map() function to read a CSV file into an assortment. To exercise this, you'll use str_getcsv every bit a callback part. This is a built-in PHP role that is used to parse a CSV string into an array.
A callback role is some executable code that is passed to another slice of code as an argument. This statement is expected to be chosen dorsum later on by the lawmaking it is passed to.
Here is how we can use array_map and str_getcsv to map our CSV data into an assortment:
<?php $csv = array_map('str_getcsv', file('data.csv')); echo '<pre>'; print_r($csv); echo '</pre>'; ?> The above code uses the file() method to read the CSV file into an array of lines. Then, with assortment map, it calls str_getcsv() on each line and stores the data for the unabridged file in $csv. The str_getcsv() office parses the CSV field contents of each line into an array.
The output of the above code snippet volition be the aforementioned as above.
Notice how much less lawmaking 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 similar fopen() and fgetcsv() and converting the CSV fields into an array. I showed you ii means to do this.
Now, effort doing it yourself. Happy coding!
Did you detect this post useful?
Source: https://code.tutsplus.com/articles/read-a-csv-to-array-in-php--cms-39471
0 Response to "W3c Php Turn a Csv File to an Array Without Uploading File."
Post a Comment