download dynamic csv using php and oracle

The code below shows the way to generate a dynamic csv file using php in download format.

<?PHP
    error_reporting(0);
    set_time_limit(0);
   
   
   
    if ($conn =OCILogon("username", "password", "DB")) {
       
        $sql = "SELECT * FROM EMPLOYEE";
       
    } else {
      $err = OCIError();
      echo "Oracle Connect Error " . $err[text];
    }
   
    Downloadfile('mySample.csv');
   
        $header = "";
        $data ="";
        $line = "";

        for ($i = 0; $i < oci_field_name($sql); $i++) {
            $line .= '"'.oci_field_name($sql, $i).'",';
        }
       
        $header = substr(trim($line), 0, -1)."\n";
       
       
        $stid = OCIParse($conn, $sql);
        OCIExecute($stid, OCI_DEFAULT);
        while ($succ = OCIFetchInto($stid, $row)) {
            $line = "";
            for ($i = 0; $i < sizeof($row); $i++) {
                $line .= '"'.$row[$i].'",';
            }
            $data .= substr(trim($line), 0, -1)."\n";
        }

print $header."\n".$data;
exit;

OCILogoff($conn);

?>

<?php

function Downloadfile($filename) {
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=$filename" );
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
    header("Pragma: public");
}

?>

No comments:

Post a Comment