Saturday, May 14, 2016

PHP: Serve up a CSV file from SQL Server

Here's a simple PHP script to build a CSV file to be sent to the users. The script is designed to work with all SQL statements by dynamically determining the column names and # of columns. Note that datetime is returned as a string such that no additional post-processing is necessary.

    // connect to sql server
    $connInfo = array('Database' => 'database_name',
                      'UID'      => 'sqlsvr_login',
                      'PWD'      => 'password',
                      'ReturnDatesAsStrings' => true);
    $mssql = sqlsrv_connect('sqlserver', $connInfo);
    if ($mssql === false) {
        die('<pre>' . print_r(sqlsrv_errors(), true) . '</pre>');
    }
    // execute the stored procedure to get the report data
    $sql = 'SELECT xxx FROM xxx WHERE xxx';
    $res = sqlsrv_query($mssql, $sql);
    if ($res === false) {
        die('<pre>' . print_r(sqlsrv_errors(), true) . '</pre>');
    }
    // get the column names
    $cols = sqlsrv_field_metadata($res);
    $ncol = sqlsrv_num_fields($res);
    $content = '';
    for ($i = 0; $i < $ncol; $i++) {
        if ($i > 0) $content .= ',';
        $content .= $cols[$i]['Name'];
    }
    $content .= "\n";
    // get the rows
    while ($row = sqlsrv_fetch($res)) {
        for ($i = 0; $i < $ncol; $i++) {
            if ($i > 0) $content .= ',';
            $content .= sqlsrv_get_field($res, $i);
        }
        $content .= "\n";
    }
    // we are done
    sqlsrv_free_stmt($res);
    sqlsrv_close($mssql);
    // write to the file
    file_put_contents($file, $content);

    // start sending the results back to the user
    header('Content-Disposition: attachment; filename="some.csv"');
    header('Content-Length: ' . filesize($file));
    header('Content-Type: application/octet-stream;');
    readfile($file);



No comments:

Post a Comment