Last active
June 25, 2019 07:42
-
-
Save fhdalikhan/7d4c8d5ec9b1ef20a275c8f868a0df18 to your computer and use it in GitHub Desktop.
export csv in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function export(){ | |
| $filename = uniqid().".csv"; | |
| header("Content-Disposition: attachment; filename=\"$filename\""); | |
| header("Content-Type: application/vnd.ms-excel"); | |
| /* Connect to a MySQL database using driver invocation */ | |
| $dsn = 'mysql:dbname=test_db;host=127.0.0.1'; | |
| $user = 'test'; | |
| $password = 'test'; | |
| try { | |
| $dbh = new PDO($dsn, $user, $password); | |
| } catch (PDOException $e) { | |
| echo 'Connection failed: ' . $e->getMessage(); | |
| } | |
| $sql = "SELECT * FROM TABLE_NAME"; | |
| $sth = $dbh->prepare($sql); | |
| $sth->execute(); | |
| $result = $sth->fetchAll(PDO::FETCH_ASSOC); | |
| $columns = [ | |
| 'category_name', | |
| 'product_name', | |
| 'product_price', | |
| 'product_detail', | |
| 'product_detail_desc', | |
| ]; | |
| $headerText = ''; | |
| foreach ($columns as $column) { | |
| $headerText .= $column . ','; | |
| } | |
| $headerText = rtrim($headerText, ','); | |
| echo $headerText . "\r\n"; | |
| foreach($result as $rowArray){ | |
| $category_name = $rowArray['category_name']; | |
| $product_name = $rowArray['product_name']; | |
| $product_price = $rowArray['product_price']; | |
| $product_detail = $rowArray['product_detail']; | |
| $product_detail_desc = $rowArray['product_detail_desc']; | |
| echo '"'.$category_name . '",'; | |
| echo '"'.$product_name . '",'; | |
| echo '"'.$product_price . '",'; | |
| echo '"'.(strip_tags(html_entity_decode($product_detail))) . '",'; | |
| echo '"'.(strip_tags(html_entity_decode($product_detail_desc))) . '"' . "\r\n"; | |
| } | |
| } | |
| export(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment