How to Convert CSV data to array with php.
CSV (Comma-separated values) is a popular format for storing tabular data. It is easy to read and write, and it can be used by a variety of software applications.
In PHP, there are a few different ways to convert CSV data to an array. One way is to use the fgetcsv() function. This function takes a CSV string as input and returns an array of the values in the CSV data.
Here is an example of how to use the fgetcsv() function to convert CSV data to an array:
function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 1000, ',');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
throw new Exception($file . ' doesn`t exist or is not readable.');
}
return $rows;
}
$data = csvToArray('data.csv');
foreach ($data as $value) {
print_r($data);
This code will first import the fgetcsv() function from the fgetcsv.php file. Then, it will get the CSV data from a string. Next, it will convert the CSV data to an array using the fgetcsv() function. Finally, it will print the array.
The fgetcsv() function takes three arguments:- The first argument is the CSV data as a string.
- The second argument is the maximum number of characters to read.
- The third argument is the delimiter character.
The fgetcsv() function will return an array of the CSV data. The array will have one element for each row in the CSV data. Each element in the array will be an array of the values in the row.
Here is an explanation of the code:-
The require_once() function
imports the
fgetcsv() function from the
fgetcsv.php file.
-
The csv_data variable stores
the CSV data as a string.
-
The array variable stores
the converted CSV data as an array.
-
The rows variable stores a
row of the CSV data as an array.
-
The fgetcsv() function is
used to convert the CSV data to an array.
-
The while loop iterates
through the CSV data and adds each row to the array variable.
- The print_r() function is used to print the array variable.
Post a Comment