Foros del Web » Programando para Internet » PHP »

Exportar tabla a CSV

Estas en el tema de Exportar tabla a CSV en el foro de PHP en Foros del Web. hola, tengo este script con el que quiero exportar una tabla de mi base de datos, a un archivo CSV. Código PHP: <?php   include( ...
  #1 (permalink)  
Antiguo 11/12/2009, 16:30
Diegotopet
Invitado
 
Mensajes: n/a
Puntos:
Pregunta Exportar tabla a CSV

hola, tengo este script con el que quiero exportar una tabla de mi base de datos, a un archivo CSV.

Código PHP:
<?php
 
include("db.php"); // archivo de conexión a base de datos
require 'exportcsv.inc.php';
$table="Mi_TABLA"// this is the tablename that you want to export to csv from mysql.
 
exportMysqlToCsv($table);
 
?>
Y este es el archvo exportcsv.inc.php
Código PHP:
<?php
 
function exportMysqlToCsv($table,$filename "photo_order_report.csv")
{
    
$csv_terminated "\n";
    
$csv_separator ",";
    
$csv_enclosed '"';
    
$csv_escaped "\\";
    
$sql_query "select * from $table";
 
    
// Gets the data from the database
    
$result mysql_query($sql_query);
    
$fields_cnt mysql_num_fields($result);
 
 
    
$schema_insert '';
 
    for (
$i 0$i $fields_cnt$i++)
    {
        
$l $csv_enclosed str_replace($csv_enclosed$csv_escaped $csv_enclosed,
            
stripslashes(mysql_field_name($result$i))) . $csv_enclosed;
        
$schema_insert .= $l;
        
$schema_insert .= $csv_separator;
    } 
// end for
 
    
$out trim(substr($schema_insert0, -1));
    
$out .= $csv_terminated;
 
    
// Format the data
    
while ($row mysql_fetch_array($result))
    {
        
$schema_insert '';
        for (
$j 0$j $fields_cnt$j++)
        {
            if (
$row[$j] == '0' || $row[$j] != '')
            {
 
                if (
$csv_enclosed == '')
                {
                    
$schema_insert .= $row[$j];
                } else
                {
                    
$schema_insert .= $csv_enclosed 
                    
str_replace($csv_enclosed$csv_escaped $csv_enclosed$row[$j]) . $csv_enclosed;
                }
            } else
            {
                
$schema_insert .= '';
            }
 
            if (
$j $fields_cnt 1)
            {
                
$schema_insert .= $csv_separator;
            }
        } 
// end for
 
        
$out .= $schema_insert;
        
$out .= $csv_terminated;
    } 
// end while
 
    
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    
header("Content-Length: " strlen($out));
    
// Output to browser with appropriate mime type, you choose ;)
    
header("Content-type: text/x-csv");
    
//header("Content-type: text/csv");
    //header("Content-type: application/csv");
    
header("Content-Disposition: attachment; filename=$filename");
    echo 
$out;
    exit;
}
?>
pero al ejecutarlo me salen los siguientes errores

---------------------------------

Warning: Cannot modify header information - headers already sent by (output started at /home/content/v/a/d/vadvent/html/photos/login/index.php:7) in /exportcsv.inc.php on line 61

Warning: Cannot modify header information - headers already sent by (output started at /home/content/v/a/d/vadvent/html/photos/login/index.php:7) in /exportcsv.inc.php on line 62

Warning: Cannot modify header information - headers already sent by (output started at /home/content/v/a/d/vadvent/html/photos/login/index.php:7) in /exportcsv.inc.php on line 64

Warning: Cannot modify header information - headers already sent by (output started at /home/content/v/a/d/vadvent/html/photos/login/index.php:7) in /exportcsv.inc.php on line 67


no se por que, ni como solucionarlo, alguien sabe como?
  #2 (permalink)  
Antiguo 11/12/2009, 16:36
Avatar de bacdavi  
Fecha de Ingreso: junio-2006
Ubicación: http://localhost/
Mensajes: 351
Antigüedad: 17 años, 10 meses
Puntos: 7
Respuesta: Exportar tabla a CSV

mira yo uso este script que yo mismo realice:

Código PHP:
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=archivo.csv");
header("Content-Transfer-Encoding: binary");
header("Content-Type: application/octet-stream");
$sql_body="SELECT * FROM tu_tabla";
mysql_query ("SET NAMES 'utf8'");
$body_qry=@mysql_query($sql_body);

//Declaro el encabezado
$res="Descripcion,Tarjeta,Monto,Email,Nombre Cliente,Referencia Cliente,Autorizacion,Respuesta";
echo 
$res."\r\n";
//
while($body=@mysql_fetch_array($body_qry)){
    
$tarjeta=EnviarClave($body["client_cc_num"],1);
    
$fecven=EnviarClave($body["client_cc_fve"],1);
    echo 
$body["vng_payment_service"].',************'.substr($tarjeta,12,15).','.$body["client_amount"].','.$body["client_email"].','.$body["vng_client_name"].','.$body["client_reference"].','.$body["vng_payment_authno"].','.$body["vng_payment_descrip"]."\r\n";

si no le entiendes me avisas! =D
  #3 (permalink)  
Antiguo 11/12/2009, 16:43
Avatar de claudiovega  
Fecha de Ingreso: octubre-2003
Ubicación: Puerto Montt
Mensajes: 3.667
Antigüedad: 20 años, 6 meses
Puntos: 11
Respuesta: Exportar tabla a CSV

Yo sacaria este código:

Código PHP:
<?php
    header
("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    
header("Content-Length: " strlen($out));
    
// Output to browser with appropriate mime type, you choose ;)
    
header("Content-type: text/x-csv");
    
//header("Content-type: text/csv");
    //header("Content-type: application/csv");
    
header("Content-Disposition: attachment; filename=$filename");
    echo 
$out;
    exit;
?>
y lo colocaría en el primer script.
  #4 (permalink)  
Antiguo 11/12/2009, 16:50
Diegotopet
Invitado
 
Mensajes: n/a
Puntos:
Exclamación Respuesta: Exportar tabla a CSV

Como, que quede asi?

Código PHP:
<?php
 
include("../../db.php"); // archivo de conexión a base de datos
require 'exportcsv.inc.php';
$table="photo_order"// this is the tablename that you want to export to csv from mysql.
 
exportMysqlToCsv($table);
    
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    
header("Content-Length: " strlen($out));
    
// Output to browser with appropriate mime type, you choose ;)
    
header("Content-type: text/x-csv");
    
//header("Content-type: text/csv");
    //header("Content-type: application/csv");
    
header("Content-Disposition: attachment; filename=$filename");
    echo 
$out;
    exit;
 
?>
Asi no funciona, me sigue saliendo el error.

Última edición por Diegotopet; 11/12/2009 a las 16:51 Razón: no funciono asi.
  #5 (permalink)  
Antiguo 11/12/2009, 17:02
Avatar de claudiovega  
Fecha de Ingreso: octubre-2003
Ubicación: Puerto Montt
Mensajes: 3.667
Antigüedad: 20 años, 6 meses
Puntos: 11
Respuesta: Exportar tabla a CSV

Este error pasa al usar la funcion header(). Esta función no se puede usar luego de enviar texto al cliente, es decir, cuando muestras html o haces un echo. También pasa cuando se muestra un error antes de header().
Verifica que algo así no pase antes de usar header().
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado




La zona horaria es GMT -6. Ahora son las 05:10.