How to Create a CSV File in PHP?

03-Apr-2023

.

Admin

How to Create a CSV File in PHP?

Hi Dev,

This post is focused on how to create a csv file in php?. step by step explain how to generate a csv file in php?. let’s discuss about export csv file in php example. We will use generate csv file in php example. follow bellow step for how to convert an array to csv file in php?.

Here, I will give the following example of create a csv file php program, we will use The fopen() this function opens a file or URL, the fputcsv() function use to formats a line as CSV and writes it to an open file and The fclose() function use to closes an open file pointer.

Example: Create a CSV File in php


I simply created csv file with Array:

index.php

<?php

header('Content-Type: text/csv');

header('Content-Disposition: attachment; filename="sample.csv"');

// create users array

$users = [

[ "id" => 1, "name" => "Hardik Savani", "email" => "hardik@gmail.com"],

[ "id" => 2, "name" => "Jaydeep Pathar", "email" => "jaydeep@gmail.com"],

[ "id" => 3, "name" => "Nikhil Thummer", "email" => "nikhil@gmail.com"]

];

// Write a file Open path

$file_Path = fopen('php://output', 'wb');

foreach ( $users as $user )

{

fputcsv($file_Path, $user);

}

// File close

fclose($file_Path);

?>

Output:

I hope it could help you...

#PHP