Example 1: php write csv
$file = fopen('demosaved.csv', 'w');
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
$data = array(
array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
);
foreach ($data as $row)
{
fputcsv($file, $row);
}
fclose($file);
Example 2: how to export php mysql data to csv through php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "test";
$con = new mysqli($host, $user, $password, $database);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
Example 3: how to export php mysql data to csv through php
<?php
require("db_connection.php");
$query = "SELECT * FROM users";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
if (mysqli_num_rows($result) > 0) {
$number = 1;
$users = '<table class="table table-bordered">
<tr>
<th>No.</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
';
while ($row = mysqli_fetch_assoc($result)) {
$users .= '<tr>
<td>'.$number.'</td>
<td>'.$row['first_name'].'</td>
<td>'.$row['last_name'].'</td>
<td>'.$row['email'].'</td>
</tr>';
$number++;
}
$users .= '</table>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Export Data from MySQL to CSV Tutorial | iTech Empires</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Export Data from MySQL to CSV</h2>
</div>
</div>
<div class="form-group">
<?php echo $users ?>
</div>
<div class="form-group">
<button onclick="Export()" class="btn btn-primary">Export to CSV File</button>
</div>
<script>
function Export()
{
var conf = confirm("Export users to CSV?");
if(conf == true)
{
window.open("export.php", '_blank');
}
}
</script>
</div>
</body>
</html>