Create CSV File In PHP Using Database Query

This is simple way to Create CSV File In PHP Using Database Query.

If you want to create file dynamically. This code is helpfull for you.


<?php
$con =  new mysqli('127.0.0.1','root','pinturp1','usedb');
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

$sql = "SELECT id,fname,lname,gender FROM test";
$result = $con->query($sql);

$OutputBuffer = "";
$ExportDestinationPathWebServer = $_SERVER['DOCUMENT_ROOT'].'/pintu/uploads';
$inpFileName = "test.csv";
$OutputBuffer = "Unique ID,First Name,Last Name,Gender".CHR(13);

/*If file already found delete it from directory*/
try {
    if(file_exists($ExportDestinationPathWebServer.'/'.$inpFileName)) {
        unlink($ExportDestinationPathWebServer.'/'.$inpFileName);
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}

$fh = fopen($ExportDestinationPathWebServer.'/'.$inpFileName, 'a') or die("can't open file");
fwrite($fh, $OutputBuffer);
while($row = $result->fetch_array()) {
    $OutputBuffer = $row["id"].','.$row["fname"].','.$row["lname"].','.$row["gender"].CHR(13);
    fwrite($fh, $OutputBuffer);
}
fclose($fh);
?>

Comments

Popular posts from this blog

Login with facebook using coldfusion

Create CSV file in Coldfusion Using CFFile

Get Previous One Day Data in Sql Server