Generate csv using php and oracle

Below is the code which can be readily used to generate a .csv file using php. Also this file shows the way to write data to a file using php.

The user can just copy and paste this code to generate csv file using php.

This code also shows way to connect to oracle database using php

<?PHP
    error_reporting(0);
    set_time_limit(0);
   
     
    if ($conn =OCILogon("user", "pwd", "DB")) {
       
        //$sql = "SELECT * FROM USERS";
        $sql = "SELECT * FROM employee";

       
    } else {
      $err = OCIError();
      echo "Oracle Connect Error " . $err[text];
    }
   
    //HeaderingDnload('report.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;

$fh = fopen('c:\mySample.csv', 'w') or die("can't open file");
$stringData =  $header."\n".$data;
fwrite($fh, $stringData);
fclose($fh);

OCILogoff($conn);
exit;
?>

No comments:

Post a Comment