Open In App

PHP | fputcsv( ) Function

The fputcsv() function in PHP is an inbuilt function which is used to format a line as CSV(comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.

Syntax:



int fputcsv ( $file, $fields, $separator, $enclosure )

Parameters: The fputcsv() function in PHP accepts four parameters as explained below.

Return Value: This function returns the length of the written string on success or FALSE on failure.



Exceptions:

Below programs illustrate the fputcsv() function:
Program 1:




<?php
// Sample data for formatting in CSV format
$employees = array("Raj, Singh, Developer, Mumbai",
                    "Sameer, Pandey, Tester, Bangalore",
                    "Raghav, Chauhan, Manager, Delhi");
  
// opening the file "data.csv" for writing
$myfile = fopen("gfg.csv", "w");
  
// formatting each row of data in CSV format 
// and outputting it
foreach ($employees as $line)
{
    fputcsv($myfile, explode(',',$line));
}
  
// closing the file
fclose($myfile); 
?>

Output:

Raj, Singh, Developer, Mumbai
Sameer, Pandey, Tester, Bangalore
Raghav, Chauhan, Manager, Delhi

Program 2:




<?php
// Sample data for formatting in CSV format
$random_data = array(
array("abc, efg, jhi, klm"),
array("123, 456, 789"),
array("11aa, 22bb, 33cc, 44dd")
);
  
// opening the file "data.csv" for writing
$myfile = fopen("gfg.csv", "w");
  
// formatting each row of data in CSV format 
// and outputting it
foreach ($random_data as $line)
{
    fputcsv($myfile, $line);
}
  
// closing the file
fclose($myfile);
?>

Output:

abc, efg, jhi, klm
123, 456, 789
11aa, 22bb, 33cc, 44dd

Reference: http://php.net/manual/en/function.fputcsv.php


Article Tags :