PHP fputcsv() Function
The PHP fputcsv() function formats a line (passed as a fields array) as CSV and writes it (terminated by a newline) to the specified file stream.
Syntax
fputcsv(stream, fields, separator, enclosure, escape, eol)
Parameters
stream |
Required. Specify a valid file pointer to a file successfully opened by or fsockopen() (and not yet closed by fclose()). |
fields |
Required. Specify an array of strings. |
separator |
Optional. Specify the field delimiter (one single-byte character only). Default is comma ( , ) |
enclosure |
Optional. Specify the field enclosure character (one single-byte character only). Default is ". |
escape |
Optional. Specify the field escape character (at most one single-byte character). Default is backslash (\). An empty string ("") disables the proprietary escape mechanism. |
eol |
Optional. Specify the custom End of Line sequence. Default is backslash (\n). |
Return Value
Returns the length of the written string or false on failure.
Example: fputcsv() example
The example below shows the usage of fputcsv() function.
<?php $list = array ( array('EmpID','Name','Age','Salary'), array(1,'John',25,3000), array(2,'Marry',24,2750), array(3,'Jo',27,2800) ); //opening the CSV file in write mode $fp = fopen("data.csv", "w"); //formats $list as CSV and writes //it to the CSV stream foreach ($list as $fields) { fputcsv($fp, $fields); } //closing the file fclose($fp); //getting the content of the file as CSV string $csvStr = file_get_contents('data.csv'); //displaying the CSV string echo $csvStr; ?>
The output of the above code will be:
EmpID,Name,Age,Salary 1,John,25,3000 2,Marry,24,2750 3,Jo,27,2800
❮ PHP Filesystem Reference