+

PHP Fputcsv () Function

Syntax:
int fputcsv ($file, $fields, $separator, $enclosure)
Parameters:The PHP function takes four parameters, as described below.
  • $file:This is a required parameter and specifies the file.
  • $fields:is a required parameter that specifies from which array to receive data.
  • $separator:is an optional parameter that specifies the separator fields. By default, the fputcsv() function uses a comma.
  • $enclosure:is an optional parameter that specifies the enclosure character for the field. By default, the function uses.
Return value:This function returns the length of the written string on success, or FALSE on error.Exceptions:
  • If the field contains an attachment character, it will be escaped by doubling it, unless it is preceded by escape_char.
  • Include the auto_detect_line_endings configuration parameter in runtime can help solve the problem of correctly recognizing line endings in PHP when reading files on or on a Macintosh computer.
The following programs illustrate the function:
Program 1 :
// Example of data to be formatted in CSV format $employees = array ( " Raj, Singh, Developer, Mumbai " , "Sameer, Pandey, Tester, Bangalore" , " Raghav, Chauhan, Manager, Delhi " );  
// open the file & quot; data.csv & quot; for writing $myfile = fopen ( "gfg.csv" , "w" );  
// format each line of data in CSV format
// and display it foreach (< / code> $employees as $line ) { fputcsv ( $myfile , explode ( `,` , $line )); }  
// close the file fclose ( $myfile ); ?>
Output:
Raj, Singh , Developer, Mumbai Sameer, Pandey, Tester, Bangalore Raghav, Chauhan, Manager, Delhi
Program 2:
// Sample data for CSV formatting $random_data = array ( array ( "abc, efg, jhi, klm" ), array ( "123, 456, 789" ), array ( "11aa, 22bb, 33cc, 44dd" ) );  
// open the file & quot; data.csv & quot; for writing $myfile = fopen ( "gfg.csv" , "w" );  
// format each line of data in CSV format
// and display it foreach (< / code> $random_data as $line ) { fputcsv ( $myfile , $line ); }  
// close the file fclose ( $myfile ); ?>
Output:
abc, efg , jhi, klm 123, 456, 789 11aa, 22bb, 33cc, 44dd
Link: http://php.net/manual/en/function.fputcsv.php
Get Solution for free from DataCamp guru