Home > Backend Development > PHP Tutorial > How to Convert a Multi-Dimensional Array into a CSV File?

How to Convert a Multi-Dimensional Array into a CSV File?

Barbara Streisand
Release: 2024-11-10 02:51:02
Original
1037 people have browsed it

How to Convert a Multi-Dimensional Array into a CSV File?

Convert Array into CSV

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);
}
Copy after login

Utilizing this function, the array can be converted into a CSV file using the following code:

$csvData = arrayToCsv($array);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template