fputcsv() formats an array as a CSV record and writes it to an open stream. In PHP 8.4+, provide the escape argument explicitly rather than relying on its deprecated default.
$fp = fopen('data.csv', 'w');
$row = ['id', 'name', 'score'];
fputcsv($fp, $row, ',', '"', '');
fclose($fp);fputcsv($stream, $fields, ',', '"', '')
The separator, enclosure, escape and end-of-line controls are optional, but in PHP 8.4+ the escape argument should be supplied explicitly.
<?php
$a= array(array("path"=>"php_tutorial","section"=>"php"),
array("path"=>"sql_tutorial","section"=>"sql"),
array("path"=>"javascript_tutorial","section"=>"js"),
array("path"=>"html_tutorial","section"=>"html"),
);
$f_pointer=fopen("website.csv","w"); // file pointer
foreach ($a as $fields) {
fputcsv($f_pointer, $fields, ',', '"', '');
}
fclose($f_pointer);
?>
<?php
require "config.php"; // database connection
$fp = fopen('student.csv', 'w');
$query = $dbo->prepare("select * FROM student");
$query->execute();
for($i=0; $row = $query->fetch(PDO::FETCH_NUM); $i++){
fputcsv($fp, $row, ',', '"', '');
}
fclose($fp); // Closing file pointer
?>
<?Php
require "config.php"; // Database Connetion
$sql= "SELECT * from student ";
if(strlen($sql) <6){echo "No Query ";
exit;
}
$filename='student.csv';
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$STH = $dbo->prepare($sql);
$STH->execute();
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
$headers = array_map('ucfirst', $headers); // optional, capitalize first letter of headers
fputcsv($fp, $headers, ',', '"', ''); // put the headers
fputcsv($fp, array_values($first_row), ',', '"', ''); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp, $row, ',', '"', ''); // push the rest
}
fclose($fp);
?>
In above code config.php file stores the database connection and login details. <?Php
require "config-mysqli.php"; // Database Connetion
$sql= "SELECT * FROM student "; // Query
$filename='student.csv'; // file name
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
if($stmt = $connection->query("$sql")){
$no_of_columns=$stmt->field_count;
$row = mysqli_fetch_assoc($stmt);
fputcsv($fp, array_keys($row), ',', '"', ''); // put headers
fputcsv($fp, array_values($row), ',', '"', ''); // put the first row
while ($row = $stmt->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, $row, ',', '"', '');
}
fclose($fp);
}else{
echo $connection->error;
}
?>
student.csv Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.