How to Convert an Associative Array to CSV PHP Code Examples

PHP Code to Convert Associative Array to CSV File

$f = fopen('employees.csv', 'a'); // Configure fopen to create, open, and write data.
 
fputcsv($f, array_keys($employees_array[0])); // Add the keys as the column headers
 
// Loop over the array and passing in the values only.
foreach ($employees_array as $row)
{
    fputcsv($f, $row);
}
// Close the file
fclose($f);

CSV PHP Code Examples and Learning Path

PHP has built-in functions that can help to convert an array to csv in PHP. PHP File handling module provides useful functions for creating, updating, and deleting different types of files. A Comma-separated file or CSV is one of the most important file formats, and some native PHP functions help us work with these files. These functions are.

Let’s first review these functions as they are building blocks of what we’ll see in the upcoming example.

PHP fopen – array to csv php

PHP fopen function opens an existing file or creates a new file. Here’s the function’s signature

fopen(string $filename, string $mode,bool $use_include_path = false, resource $context = ?): resource

You can see a detailed description of this function in the PHP documentation. Here we will see the most relevant arguments that are.

  • $filename  –  The file path (Example: “./my_file.csv”)
  • $mode       –  Determines the type of access to files.

Through the $mode argument, we can specify whether we want to read, write or append to the file. Here are some common modes for fopen.

ModeDescription
“r”Open the file for reading only.
“r+”Open the file for reading and writing.
‘w“Open the file for writing only.
“w+”Open the file for writing and reading.
“a”Append to the file.
fopen modes

This function opens a file or creates a new one if it doesn’t exist already. In case of a failure, the function returns false.

PHP fputcsv – array to csv php

PHP fputcsv function formats a line as csv and writes it to a file. The function’s signature is as follows.

fputcsv( resource $handle, array $fields, string $separator = ",", string $enclosure = '"', string $escape_char = "\\"): int|false

The two important arguments are.

  • $handle –  The file handler returned from the function fopen.
  • $fields   –   An array to be written to the file.

On success, the function returns the length of the written string. Else, it returns false.

PHP fclose – array to csv php

PHP fclose function is used to close a file after writing to it. It is always a best practice to close a file if it is not used any further. Here’s the function’s signature.

fclose(resource $stream): bool

On passing the file handler to the $stream argument, fclose will close the file.

Convert associative array to csv in PHP

As we’ve seen the relevant functions, let’s put them together to write out an associative array to a csv file. The associative array that we’ll be converting contains information about employees. Here’s how it looks.

//An array containing employees data.
$employees_array  = Array
(
    Array
        (
            "Id" => 1,
            "Name" => "Steve",
            "Job" => "Full Stack Developer",
            "Experience" => 5
 
        ),
 
    Array
        (
            "Id" => 2,
            "Name" => "Bob",
            "Job" =>  "Android Developer",
            "Experience" => 4
 
                ),
 
    Array
        (
            "Id" => 3,
            "Name" => "Jenny",
            "Job" =>  "UI/UX Designer",
            "Experience" => 3
 
        )
 
    );

Here’s the code that converts the associative array to csv in PHP.

$f = fopen('employees.csv', 'a'); // Configure fopen to create, open, and write data.
 
fputcsv($f, array_keys($employees_array[0])); // Add the keys as the column headers
 
// Loop over the array and passing in the values only.
foreach ($employees_array as $row)
{
    fputcsv($f, $row);
}
// Close the file
fclose($f);

Example Breakdown

  1. The fopen function creates a csv file employee.csv in append mode.
  2. For headers, fputcsv get the keys of the associative array using array_key function.
  3. The foreach loops through an array and gets each employee’s data. 
  4. The fputcsv within the foreach loop writes the data to the file.
  5. Finally, fclose closes the file after the write operation completes.

PHP Output results from converting array to CSV file

Here’s the output.

Id,Name,Job,Experience
1,Steve,"Full Stack Developer",5
2,Bob,"Android Developer",4
3,Jenny,"UI/UX Designer",3

Convert PHP Associative Arrays to CSV

With three simple functions, we have converted the associative array to csv in PHP. These sorts of operations are helpful and often used to create csv files for analysis and processing. That’s it for this article, we hope that you’ve enjoyed. Stay tuned for more informative content related to PHP.

Want to explore further about PHP arrays?

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

Add to an array in PHP

Print an array in PHP

Get length of an array in PHP


© 2022 Confident.Systems