Home >Backend Development >PHP Tutorial >How to Convert a Multi-Dimensional Array into a CSV File?
Problem:
How can an array be converted into a CSV file?
Array:
The given array contains multiple levels of objects and arrays, and its structure resembles a database table.
Solution:
To convert such an array into a CSV file, a function like arrayToCsv() can be used. This function takes an array as input and generates a CSV string by appropriately formatting and escaping the fields.
Implementation:
/** * Formats a line (passed as a fields array) as CSV and returns the CSV as a string. * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120 */ function arrayToCsv(array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false) { $delimiter_esc = preg_quote($delimiter, '/'); $enclosure_esc = preg_quote($enclosure, '/'); $output = array(); foreach ($fields as $field) { if ($field === null && $nullToMysqlNull) { $output[] = 'NULL'; continue; } // Enclose fields containing $delimiter, $enclosure or whitespace if ($encloseAll || preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field)) { $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure; } else { $output[] = $field; } } return implode($delimiter, $output); }
Utilizing this function, the array can be converted into a CSV file using the following code:
$csvData = arrayToCsv($array);
Output:
The $csvData variable will now contain the CSV string representation of the array, which can be further processed, written to a file, or integrated with appropriate applications. By employing this approach, the provided multi-dimensional array can be efficiently converted into a CSV format.
The above is the detailed content of How to Convert a Multi-Dimensional Array into a CSV File?. For more information, please follow other related articles on the PHP Chinese website!