Vishal Patel
Vishal Patel

Reputation: 71

create excel file of database query result in php

I create excel file using php.It has contain Query Result data from database.Excel file generate and download very well but when i opened i found it gives some format error and some coding error also. enter image description here

function generate_excel($conn) {
 $filename = "website_data_" . date('Ymd') . ".xls";

 function cleanData(&$str) {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if (strstr($str, '"'))
        $str = '"' . str_replace('"', '""', $str) . '"';
}

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-type: application/octet-stream;charset=utf-8");

 $flag = false;
 $qry = "SELECT ContactId,UniqueContactId FROM Contacts ORDER BY ContactId  ";
 $stmt = sqlsrv_query($conn, $qry);
 $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

while (false !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
    if (!$flag) {
        // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\r\n";
        $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
}
exit;
}

Upvotes: 1

Views: 160

Answers (1)

AVK
AVK

Reputation: 645

sqlsrv_fetch_array() can return either NULL or FALSE. You can make your while statement as follows:

while (NULL !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
    if(!$row)
        break ;

    //...
}

Here's PHP function reference: http://php.net/manual/en/function.sqlsrv-fetch-array.php

Upvotes: 1

Related Questions