Convert PHP multidimensional array to CSV with fputcsv code examples

How to Convert PHP multidimensional array to CSV This article explores how to convert PHP multidimensional array to CSV. You can skip to the final section if you’re already familiar with reading and writing CSV files in PHP. <?php $employees = [ ['Id', 'Name', 'Age', 'Salary', 'Department'], ['1', 'Anna', '30', 20000, 'Finance'], ['2', 'Adam', '25', 15000, 'IT'], ['3', 'Bob', '32', 25000, 'Finance'], ['4', 'Cara', '20', 12000, 'Logistics'], ['5', 'Daniel', '28', 27000, 'Engineering'], ]; //Creates a new file employee_records.csv $file = fopen('employee_records.csv', 'w'); //w is the flag for write mode. if($file === false) { die('Cannot open the file'); } foreach($employees as $employee) { //Formats the employee record as CSV and writes it out employee_records.csv fputcsv($file, $employee); } //Closes the file. fclose($file); ?> Introduction PHP multidimensional arrays can be complex in structure as they have arrays within. These arrays are typically called “sub-arrays”, which may or may not be consistent in data…