2017-03-09 10 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

関連する問題