php editor Xiaoxin introduces you how to format data rows into CSV and write file pointers. CSV is a commonly used data format, the abbreviation of Comma-Separated Values. Through PHP's built-in functions and methods, we can easily format the data rows into CSV format and write them into the file pointer to export and save the data. Next, let’s take a look at the specific implementation method!
Format rows to CSV and write file pointer
Step 1: Open the file pointer
$file = fopen("path/to/file.csv", "w");
Step 2: Convert rows to CSV string
Convert rows to CSV String
using the fputcsv() function. This function accepts the following parameters:
$file
: file pointer$fields
: CSV fields as array$delimiter
: Field delimiter (optional)$enclosure
: field quotes (optional) Example:
$fields = array("Name", "Age", "Occupation"); $csv = fputcsv($file, $fields);
Step 3: Write CSV string to file pointer
fwrite($file, $csv);
Step 4: Close the file pointer
fclose($file);
Example
$file = fopen("path/to/file.csv", "w"); $fields = array("Name", "Age", "Occupation"); foreach ($data as $row) { $csv = fputcsv($file, $row); fwrite($file, $csv); } fclose($file);
Precautions
fopen()
before writing to it. fputcsv()
The function will automatically add quotes and escape special characters, but you can specify custom delimiters and quotes in the call. eol
parameter of fputcsv()
to specify a custom newline character. The above is the detailed content of PHP format rows to CSV and write file pointer. For more information, please follow other related articles on the PHP Chinese website!