Created
November 5, 2015 19:47
-
-
Save adanzilla/a5415024b2a36b3b2d30 to your computer and use it in GitHub Desktop.
PHP - PDO exporta a CSV
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 | |
include_once('conn.php' ); | |
require_once(__DIR__.'/ForceUTF8/Encoding.php'); | |
use ForceUTF8\Encoding; | |
$resultado = new stdClass(); | |
$sql = 'DESCRIBE tabla'; | |
$query = $pdo->prepare($sql); | |
$rs = $query->execute(); | |
if( $rs!=false ){ | |
$headers = $query->fetchAll(PDO::FETCH_COLUMN); | |
foreach ($headers as $header) { | |
$hd .= $header."\t"; | |
} | |
} | |
$sql = 'SELECT * FROM tabla'; | |
$query = $pdo->prepare($sql); | |
$rs = $query->execute(); | |
if($rs!=false){ | |
$resultados = $query->fetchAll(PDO::FETCH_ASSOC); | |
foreach ($resultados as $row){ | |
$line = ''; | |
foreach($row as $value){ | |
if(!isset($value) || $value == ""){ | |
$value = "\t"; | |
}else{ | |
$value = str_replace('"', '""', $value); | |
$value = '"' . $value . '"' . "\t"; | |
} | |
$line .= $value; | |
} | |
$data .= trim($line)."\n"; | |
$data = str_replace("\r", "", $data); | |
if ($data == "") { | |
$data = "\nSIN RESULTADOS\n"; | |
} | |
} | |
} | |
$data = Encoding::toUTF8($data); | |
$data = Encoding::toISO8859($data); | |
header("Content-type: application/vnd.ms-excel; charset=utf-8"); | |
header("Content-Disposition: attachment; filename=registros_PROYECTO_".date('y-m-d').".xls"); | |
header("Pragma: no-cache"); | |
header("Expires: 0"); | |
// output data | |
echo $hd."\n".$data; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment