PHP Tutorial - PHP fputcsv() Function






Definition

The fputcsv() function formats a line as CSV and writes it to an open file.

Syntax

PHP fputcsv() Function has the following syntax.

fputcsv(file,fields,seperator,enclosure)

Parameter

ParameterIs RequiredDescription
fileRequired.Open file to write to
fieldsRequired.Specifies which array to get the data from
separatorOptional.A character that specifies the field separator. Default is comma ( , )
enclosureOptional.A character that specifies the field enclosure character. Default is "




Return

This function returns the length of the written string, or FALSE on failure.

Example

formats a line as CSV and writes it to an open file


<?php/* w w  w.jav a 2  s. c om*/
$list = array("A,B,C,D","E,F,G,H",);

$file = fopen("contacts.csv","w");

foreach ($list as $line){
  fputcsv($file,split(',',$line));
}

fclose($file); 
?>




Example 2

The following code shows how to format a line as CSV and writes it to an open file.


//w  w w .  j a  v a2s .c om
<?php
    $list = array("XML,HTML,CSS,Java","A,B,C,D",);
    $file = fopen("contacts.csv","w");
    foreach ($list as $line){
        fputcsv($file,explode(',',$line));
    }
    
    fclose($file); 
?>