繁体   English   中英

使用 php 下载 csv

[英]Download a csv using php

我正在尝试从 php 创建和下载一个 csv 文件,但它对我不起作用。 在这些情况下,我做了我一直在做的事情,我去基础,我消除了数据库中的查询和其他人,一步一步地发现问题。 所以第一个测试只是在固定路径中创建 csv,这对我有用。 当我进行更改以下载它而不是使用固定路径时,它不起作用,我不知道问题出在哪里。

不起作用的代码是:

<?php

$arreglo[0] = array("Nombre","Apellido","Animal","Fruto");
$arreglo[1] = array("Juan","Juarez","Jirafa","Jicama");
$arreglo[2] = array("Maria","Martinez","Mono","Mandarina");
$arreglo[3] = array("Esperanza","Escobedo","Elefante","Elote");
$filename ="prueba.csv";
$delimitador = ",";
$encapsulador = '"';

//asigno el header para descargar el archivo en lugar de escribirlo
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');

error_log("se supone que estoy en eso");
$f = fopen('php://memory', 'w');
foreach ($arreglo as $linea) {
    fputcsv($f, $linea, $delimitador, $encapsulador);
 }
  rewind($f);
  fclose($f);

?>

工作正常的代码是:

<?php

$arreglo[0] = array("Nombre","Apellido","Animal","Fruto");
$arreglo[1] = array("Juan","Juarez","Jirafa","Jicama");
$arreglo[2] = array("Maria","Martinez","Mono","Mandarina");
$arreglo[3] = array("Esperanza","Escobedo","Elefante","Elote");
$ruta ="prueba.csv";
$delimitador = ",";
$encapsulador = '"';

error_log("se supone que estoy en eso");
$f = fopen($ruta, 'w');
foreach ($arreglo as $linea) {
    fputcsv($f, $linea, $delimitador, $encapsulador);
 }
  rewind($f);
  fclose($f);

?>

这种方法似乎行不通。 来自 PHP 手册:“php://memory 和 php://temp 不可重用,即在流关闭后无法再次引用它们。” 在 fclose 之后,内存文件消失了。 此外,内存永远不会附加到 $filename 因此,出于两个原因,您将文件名传递给不存在的文件。

您可以更改为:

<?php
$arreglo[0] = array("Nombre","Apellido","Animal","Fruto");
$arreglo[1] = array("Juan","Juarez","Jirafa","Jicama");
$arreglo[2] = array("Maria","Martinez","Mono","Mandarina");
$arreglo[3] = array("Esperanza","Escobedo","Elefante","Elote");
$filename = "prueba.csv";
$delimitador = ",";
$encapsulador = '"';

header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');

error_log("se supone que estoy en eso");
$f = fopen("php://output", 'w');
foreach ($arreglo as $linea) {
fputcsv($f, $linea, $delimitador, $encapsulador);
}

或者如果你想保存文件:

$f = fopen( $filename, 'w');
foreach ($arreglo as $linea) {
fputcsv($f, $linea, $delimitador, $encapsulador);
}
fclose($f);

//asigno el header para descargar el archivo en lugar de escribirlo
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
readfile( $filename); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM