Create CSV File in PHP

Introduction

This article shows how to create a CSV file in PHP. CSV is a type of file and from this article you can easily create a CSV file. A CSV file is like a Microsoft Excel file but CSV files are saved with a csv extension. A CSV files are very important to us for storing data backups. I will create a CSV file to store a specific table; I will use a "courses" table and include its column names. I will use this table data like that and show in the CSV file.

cal.jpg

Example 

<?php

$T_name = 'courses';

$Str = NULL;

header("Content-Type: application/csv");

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

$Con = mysql_Connect("localhost", "root", "");

mysql_select_db("smart",$Con);

$Res = mysql_query("show columns from $T_name",$Con);

while($row = mysql_fetch_array($Res))

{

    $Str.= $row['field'].',';

$Str = substr($Str, 0, -1)."\n";

$Res = mysql_query("select * from $T_name",$Con);

while ($row = mysql_fetch_assoc($Res))

{

    $Str.= join(',', $row)."\n";

}

echo $Str;

mysql_close($Con);

?>

Output

cal1.jpg

Open your CSV file.

cal2.jpg

In the next example I will explain creation of a CSV file using fputcsv(). The fputcsv() function formats records as CSV and writes to file pointer.

Example 1

<?php

$list = array(

array('Hello', 'sir', 'how', 'are'),

array('hi', 'how', 'are'),

array('"am"', '"fine"')

);

$file= fopen('file.csv', 'w');

foreach ($list as  $Field)

{

    fputcsv($file, $Field);

}

fclose($file);

?>

Example 2

<?php

$T_name = 'courses';

$F_name = tempnam(sys_get_temp_dir(), "csv");

$Con = mysql_connect("localhost", "root", "");

mysql_select_db("smart",$Con);

$File = fopen($F_name,"w");

$Res = mysql_query("show columns from $T_name",$Con);

for ($i = 0; $i < mysql_num_rows($Res); $i++)

{

    $colArray[$i] = mysql_fetch_assoc($Res);

    $fieldArray[$i] = $colArray[$i]['Field'];

}

fputcsv($File,$fieldArray);

$Res = mysql_query("select * from $T_name",$Con);

for ($i = 0; $i < mysql_num_rows($Res); $i++)

{

    $dataArray[$i] = mysql_fetch_assoc($Res);

}

foreach ($dataArray as $line)

{

    fputcsv($File,$line);

}

fclose($File);

header("Content-Type: application/csv");

header("Content-Disposition: attachment;filename=cars-MCNSolution.csv");

readfile($F_name);

unlink($F_name);

?>

Output

fputcsv.jpg

Open your CSV file.

fputcsv1.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all