In the context of PHP scripting, how can CSV files be generated from multidimensional arrays for data storage or analysis purposes?

To generate CSV files from multidimensional arrays in PHP, you can loop through the array and use fputcsv() function to write each row to a CSV file. This function automatically formats the data and handles special characters like commas. This allows you to easily store or analyze data in a CSV format.

<?php
// Sample multidimensional array
$data = array(
    array('Name', 'Age', 'Country'),
    array('John Doe', 25, 'USA'),
    array('Jane Smith', 30, 'Canada'),
    array('Mike Johnson', 22, 'UK')
);

// Open a file for writing
$fp = fopen('data.csv', 'w');

// Loop through the array and write each row to the CSV file
foreach ($data as $row) {
    fputcsv($fp, $row);
}

// Close the file
fclose($fp);

echo 'CSV file generated successfully!';
?>