PHP format rows to CSV and write file pointer

WBOY
Release: 2024-03-22 09:04:02
forward
826 people have browsed it

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");
Copy after login

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);
Copy after login

Step 3: Write CSV string to file pointer

fwrite($file, $csv);
Copy after login

Step 4: Close the file pointer

fclose($file);
Copy after login

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);
Copy after login

Precautions

  • Make sure to open the file using 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.
  • Consider using buffering to improve performance when processing large numbers of rows in a loop.
  • Always remember to close the file pointer to release system resources.
  • If you are processing lines that contain newlines, use the 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!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!