Created
May 25, 2012 17:12
-
-
Save felipelavinz/2789263 to your computer and use it in GitHub Desktop.
quickest way to export to 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 | |
global $wpdb; | |
// obtener resultados para una consulta cualquiera | |
// el parámetro ARRAY_N indica que wpdb debe retornar los resultados | |
// como un array con índices numéricos | |
$entries = $wpdb->get_results("SELECT * FROM $wpdb->contact_form ORDER BY id DESC", ARRAY_N); | |
if ( $entries ) { | |
// abrir un archivo, en este caso un archivo temporal de hasta 12MB | |
// (si es más grande, lo escribe a un archivo) | |
$fp = fopen( 'php://temp/maxmemory:'. (12*1024*1024) , 'r+' ); | |
foreach ( $entries as $row ) { | |
fputcsv( $fp, $row ); | |
} | |
// be kind, rewind (devolver la posición del puntero del archivo) | |
rewind( $fp ); | |
// obtener contenido del archivo como un string | |
$output = stream_get_contents( $fp ); | |
// cerrar archivo | |
fclose( $fp ); | |
// cabeceras HTTP: | |
// tipo de archivo y codificación | |
header('Content-Type: text/csv; charset=utf-8'); | |
// forzar descarga del archivo con un nombre de archivo determinado | |
header('Content-Disposition: attachment; filename=contact-'. time() .'.csv' ); | |
// indicar tamaño del archivo | |
header('Content-Length: '. strlen($output) ); | |
// enviar archivo | |
echo $output; | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment