export data as csv in php code example

Example 1: php modify csv file

$myfile = 'sample_csv.csv';

$fin = fopen($myfile, 'r');
$data = array();

   /***********
   * header row
   */
$data[] = fgetcsv($fin, 1000);
  /***********
   * data rows
   */
while ($line = fgetcsv($fin, 1000)) {
   echo join(', ', $line).'<br>';
   for($i = 4, $k = count($line); $i < $k; $i++) {
    if ($line[$i] < 1000) {
	    $line[$i] = 10000;
    }
   }
   $data[] = $line;
}

fclose($fin);
   /******************
   * reopen file and
   * write array to file
   */
$fout = fopen($myfile, 'w');
foreach ($data as $line) {
   fputcsv($fout, $line);
}
fclose($fout);

Example 2: how to export php mysql data to csv through php

<?php
/*
* iTech Empires:  Export Data from MySQL to CSV Script
* Version: 1.0.0
* Page: DB Connection
*/
 
// Connection variables
$host = "localhost"; // MySQL host name eg. localhost
$user = "root"; // MySQL user. eg. root ( if your on localserver)
$password = ""; // MySQL user password  (if password is not set for your root user then keep it empty )
$database = "test"; // MySQL Database name
 
// Connect to MySQL Database
$con = new mysqli($host, $user, $password, $database);
 
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}
?>

Tags:

Php Example