Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is the fputcsv() function in PHP?

Sarvech Qadir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The fputcsv() function in PHP is a built-in function in PHP. This method is useful for formatting any line of string as a .csv format (comma-separated values).

Syntax

fputcsv ( $file, $fields, $separator, $enclosure )

Parameters

$file: The .csv file for writing values.

$fields: Arrays containing the lines of data to be formatted into .csv.

$separator: Separator that is used in the new file. We use , (comma) by default.

$enclosure: This is an optional parameter specifying the enclosure character of a field.

Return value

On success, the function returns the length of the written string. Otherwise, the function returns False.

Code

Let’s look at a coding example to understand how the fputcsv() method works.

<?php
// array of cities
$cities = array(
array("California", "Boston", "Chicago", "New York"),
array("Amsterdam", "London", "Madrid", "Paris"),
array("Islamabad", "Mumbai", "Karachi", "Dubai")
);
// opening the file "file.csv" for writing the values in it
$myfile = fopen("file.csv", "w");
// putting each line in the file.
// iterating through each individual array
foreach ($cities as $line)
{
// the second parameter should be an array
// putting each array in the file converting it into csv
fputcsv($myfile, $line);
}
// close the file
fclose($myfile);
?>

RELATED TAGS

php

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring