PHP fputcsv() function and example


 

PHP fputcsv() function and example

In this part of the tutorial we will see how to use the file handling function fputcsv and its example

In this part of the tutorial we will see how to use the file handling function fputcsv and its example

Syntax
fputcsv(file_handle,array_fields[,seperator[,enclosure]])

  • Array fields is formatted in CSV format and
  • Then write these to the CSV file using the file_handle.


Example of PHP fputcsv() Function

Code of fputcsv() Function in PHP Beginners

<?php
    $file1
=fopen("c:/rose1/rose1.csv","r");
    echo
"values before fputcsv()<br>";
    while
(($array1=fgetcsv($file1))!==FALSE)
     foreach
($array1 as $key=>$value)
     echo
" ".$value;
?>

<?php
    $list1
= array("dddd","eeee","ffff");
    $file
= fopen("c:/rose1/rose1.csv","a");
    for
($x=0;$x<sizeof($list1);$x++)
     fputcsv($file,split(',',$list1[$x]));
    fclose($file);
?>

<?php
    $file1
=fopen("c:/rose1/rose1.csv","r");
    echo
"<br>values after fputcsv()<br>";
    while
(($array1=fgetcsv($file1))!==FALSE)
     foreach
($array1 as $key=>$value)
      echo
" ".$value;
?>

Output

values before fputcsv()
name aaaa bbbb cccc
values after fputcsv()
name aaaa bbbb cccc dddd eeee ffff

Ads