Convert PHP multidimensional array to CSV with fputcsv code examples

Summary:

PHP multidimensional arrays can be converted to CSV files quickly using PHP's function fputcsv() by looping through the parent array and ensuring each child array is flattened and then passed to a stream object, e.g. fputcsv($stream, $childArray). Once the stream is closed the CSV is saved.

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);
?>

CSV PHP Code Examples and Learning Path

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 and format. The variability in dimensions and data is more frequent when data comes from a database or API.

Contrary to multidimensional, linear or one-dimensional arrays are nice and easy. You need a loop to go through the entire list and do whatever transformations you want. Similarly, if you’re converting an array to CSV in PHP, the array’s dimensions would matter. 

So, this article explores how to convert PHP multidimensional array to CSV with fputcsv. To have a solid ground, consider reading FuelingPHP’s article about reading and writing CSV in PHP. That said! Let’s get started with a quick recap of fputcsv in PHP and then move on to the core topic.

How does fputcsv work?

PHP fputcsv formats a line as CSV and writes to a file pointer. A file pointer refers to a file resource residing somewhere local or remote. Here are some pointers about the necessary arguments of this function.

  • stream refers to the file pointer.
  • array is supposed to be an array of strings – not a multidimensional array. 
  • separator defaults to “,” because CSV files are based on comma delimiters. 

PHP fputcsv either returns an integer or false in case of a failure. The integer is essentially the length of the string it reads or writes.

You can learn more about this function at the official documentation as we don’t want to overwhelm you with lots of unnecessary information. The following example demonstrates the use of fputcsv 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);
?>

If you’re baffled about functions like fopen, die or fclose – consider reading official documentation or FuelingPHP’s article that has been mentioned in the intro.

So, the example produces a CSV file as shown below.

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

The example includes an array that has a well-defined and consistent structure. The real challenge lies ahead – How to convert PHP multidimensional array to CSV. 

How to convert PHP multidimensional array to CSV

PHP fputcsv expects an array of strings which means no explicit conversion of array to string.

convert php multidimensional array to csv

So, as the image above suggests PHP cannot convert [“World”] to string. You either use a function like implode or a function that flattens an array, trying to reshape it to a linear array.

flatten php array

The flatten function brings down the array from multi to one dimension.

function flatten(array $array) {
    $output = array();
    array_walk_recursive($array, function($arr) use (&$output) { $output[] = $arr; });
    return $output;
}

Now, let’s see the multidimensional array that we’re trying to convert to PHP.

$employees = [
    ['Name'=> 'Anna', 'ReportsTo' => ['Shawn']],
    ['Name'=> 'Shawn', 'ReportsTo' => ['Drake', 'Tom']],
    ['Name'=> 'Brian', 'ReportsTo' => ['Kylie', 'Rebecca']],
];

Every employee reports to at least two managers (Manager#1, Manager#2). Let’s move on to the example that uses the flatten function to reshape the data, setting it up for the fputcsv PHP.

PHP multidimensional array to CSV

Here’s the part that converts PHP multidimensional array to CSV.

$file = fopen("output_alphabets.csv", "w");
 
fputcsv($file, ['Name', 'Manager#1', 'Manager#2' ]);
 
foreach($employees as $employee)
{
    $data = flatten($employee);  //Reshapes the employee record to [Name, Manager#1, Manager#2]
   
    fputcsv($file,$data);
}
 
fclose($file);

And here’s the output as CSV.

Name,Manager#1,Manager#2
Anna,Shawn
Shawn,Drake,Tom
Brian,Kylie,Rebecca

Voila! We have our CSV file all ready!!

Converting PHP Multidimensional Arrays to CSV

The article explores how to convert PHP multidimensional array to CSV. The example uses a generalized recursive function to deal with a multidimensional array’s varying and inconsistent structure. Generalized solutions are always preferable, but some scenarios also ask for specific measures.

While this article tries to demonstrate a generalized solution that would fit well for many problems, specialized functions are often necessary. So, always opt for generalized solutions but never shy away from specialized modules and functions. The end goal in programming and development is always about solving a problem.

Hopefully, you’ve liked this article. If you’re interested in learning more about PHP, FuelingPHP is the way to go!

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems