How to create array from a csv file using php?

by arnoldo.moen , in category: PHP General , 7 months ago

How to create array from a csv file using php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lottie , 7 months ago

@arnoldo.moen 

To create an array from a CSV file using PHP, you can use the built-in function fgetcsv() to read the CSV file line by line. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$csvFile = 'path/to/example.csv'; // Replace with the path to your CSV file

$csvData = [];

if (($handle = fopen($csvFile, 'r')) !== false) {
    while (($data = fgetcsv($handle, 1000, ',')) !== false) {
        $csvData[] = $data;
    }
    fclose($handle);
}

print_r($csvData);


In this example, fopen() is used to open the CSV file in read mode. Then, a loop reads each line using fgetcsv(), which returns an array of data for each line. The 1000 in fgetcsv() represents the maximum length of a line, and ',' specifies the separator used in the CSV file (typically a comma).


The data is then appended to the $csvData array using the [] syntax, creating a multidimensional array where each inner array represents a row from the CSV file.


Finally, fclose() is used to close the CSV file handle, and print_r() is used to display the resulting array.

Member

by ryleigh , 7 months ago

@arnoldo.moen 

Please note that the code assumes the CSV file has a comma (',') as the delimiter. If your CSV file uses a different delimiter, you can replace the ',' parameter in the fgetcsv() function with the appropriate one.