2017-03-09 95 views
1

我是PHP新手,正在嘗試創建一小段代碼,用於讀取數據庫中的表,並允許用戶將表格下載到CSV文件中。數據庫中的PHP回顯表並將它們下載爲CSV文件

到目前爲止,我已經能夠連接到我的數據庫,並通過回聲表

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 

// Check connection 
if ($conn->connect_error) { 
die("Connection failed1: " . $conn->connect_error); 
} 

// SQL query 
$sql = "SHOW TABLES IN `abc1`"; 

// perform the query and store the result 
$result = $conn->query($sql); 

// if the $result not False, and contains at least one row 
    if($result !== false) { 

     // if at least one table in result 
     if($result->num_rows > 0) { 
     // traverse the $result and output the name of the table(s) 
      while($row = $result->fetch_assoc()) { 
       echo '<br />'. $row['Tables_in_abc1']; 
      } 
     } 
else echo 'There is no table in "tests"'; 
} 
else echo 'Unable to check the "tests", error - '. $conn->error; 


$conn->close(); 
?> 

現在,我想轉的每個表變成一個鏈接,這樣當用戶點擊它,他們將能夠將表格的數據下載到CSV文件中。

我該怎麼做?

回答

2

這應該是一個評論,但我不夠高的水平離開一個。你應該看看PHPExcel。

https://github.com/PHPOffice/PHPExcel

它配備了大量的例子,這應有助於你實現你正在嘗試做的。

2

您可以將數據流式傳輸到客戶端這樣的:

header('Content-type: text/csv'); 
header('Content-disposition: attachment;filename=file.csv'); 

$stdout = fopen('php://stdout', 'w'); 
while($row = $result->fetch_assoc()) { 
    fputcsv($stdout, $row); 
} 
fclose($stdout); 

或寫入文件:

$filePath = __DIR__ .'/tmp.csv'; // for instance current folder 
$fh = fopen($filePath, 'w+'); 
while($row = $result->fetch_assoc()) { 
    fputcsv($fh, $row); 
} 
fclose($fh); 

,然後發送找到客戶端:

header('Content-type: text/csv'); 
header('Content-disposition: attachment;filename=file.csv'); 

readfile($filePath); 

http://php.net/manual/en/function.fputcsv.php

相關問題