2013-11-22 76 views
-2

我想从我的数据库中使用php中提取数据并将其导出到可下载的CSV文件中,该文件可以用excel打开。我能够做到这一点,当我使用MySQL,但是,许多人建议在我的代码中不包括mysql语法,因为它被弃用,而应该使用mysqli。我改变了我的代码,但现在我的代码无法正常工作。有谁知道这是为什么?PHP不能创建可下载的CSV文件

MySQL版本(工作版本)`

mysql_connect('localhost', 'xxxxx', 'xxxxx') or die('connect'); 
mysql_select_db('db') or die('select'); 
$result = mysql_query('SELECT * bodyshops_master_network') or die('query'); 

if(mysql_num_rows($result) == 0) 
{ 
    die('no data'); 
} 

$fh = tmpfile() or die('tmpfile'); 
$cols = array_keys(mysql_fetch_assoc($result)); 
fputcsv($fh, $cols); 
mysql_data_seek($result, 0); // set result row pointer back to first row 

while($row = mysql_fetch_assoc($result)) 
{ 
    fputcsv($fh, $row); 
} 

rewind($fh); 
$text = fread($fh, 999999); 
header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="download.csv"'); 
header('Content-Length: ' . strlen($text)); 
echo $text; 
exit; 

mysqli的版本(不工作):

$mysqli = new mysqli("localhost", "xxxxx", "xxxxx", "db"); 

if (mysqli_connect_errno()) 
{ 
    printf("Connect failed: ", mysqli_connect_error()); 
    exit(); 

} else 
{ 

$result = "SELECT * FROM bodyshops_master_network"; 
if(mysqli_num_rows($result) == 0) 
{ 
    die('no data'); 
} 

$fh = tmpfile() or die('tmpfile'); 
$cols = array_keys($result->fetch_assoc()); 
fputcsv($fh, $cols); 
$result->data_seek(0); // set result row pointer back to first row 

while($row = $result->fetch_assoc()) 
{ 
    fputcsv($fh, $row); 
} 

rewind($fh); 
$text = fread($fh, 999999); 
header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="download.csv"'); 
header('Content-Length: ' . strlen($text)); 
echo $text; 
exit; 

回答

0
  1. 检查的phpinfo看到mysqli扩展启用。

  2. 删除/注释头调用,以便您接收输出为纯HTML,以便您注意到是否有任何消息显示(由于死或编码错误)或实际获取数据。

另外请注意,你失去您检索的第一个记录的日期,因为你拨打:

$cols = array_keys(mysql_fetch_assoc($result)); 

分别

$cols = array_keys($result->fetch_assoc()); 
+0

我已经注释掉了标题调用,并且当我运行我的代码时什么也没有发生,即没有数据显示 – user3009232

+0

也检查您的服务器日志。除非你忘记粘贴上面的代码,否则你的代码在结尾处缺少一个}(关闭else if(mysqli_connect_errno())。 –

0

什么是不工作?

您是否收到任何错误?

文件是否为空,是否有任何文件正在下载?

也许没有启用的错误,试试这个:

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 
?> 
+0

什么都没有下载 – user3009232

+0

并且没有错误?你能访问apache错误日志吗? – Haudegen

+0

访问Apache的错误日志?:S – user3009232

0

我是新StackOverflow上,我认为这会有所帮助。 (我说西班牙语,我希望你能理解我的英语:D)

我一直在寻找一种简单的方法来使用mysqli并下载一个csv文件,可以通过excel读取没有UTF-8问题(使用ñ A,U ...)。我没有找到它,所以我自己创建了一个(从谷歌学习和StackOverflow的答案),几个小时后,我终于有了一些工作。

这是一个与数据库连接的类,这些函数将使用mysqli和PHP来执行任何你想要的操作。在这种情况下,调用这个类(require或include),只需使用“downloadCsv()”函数。

举个例子,这将是“class.php”文件:

<?php 
class DB{ 

private $con; 

//this constructor connects with the database 
public function __construct(){ 
$this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName"); 

if($this->con->connect_errno > 0){ 
    die('There was a problem [' . $con->connect_error . ']'); 
    } 
} 

//create the function that will download a csv file from a mysqli query 

public function downloadCsv(){ 

$count = 0; 
$header = ""; 
$data = ""; 
//query 
$result = $this->con->query("SELECT * FROM Your_TableName"); 
//count fields 
$count = $result->field_count; 
//columns names 
$names = $result->fetch_fields(); 
//put column names into header 
foreach($names as $value) { 
    $header .= $value->name.";"; 
    } 
} 
//put rows from your query 
while($row = $result->fetch_row()) { 
    $line = ''; 
    foreach($row as $value)  { 
     if(!isset($value) || $value == "") { 
      $value = ";"; //in this case, ";" separates columns 
    } else { 
      $value = str_replace('"', '""', $value); 
      $value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too 
     } 
     $line .= $value; 
    } //end foreach 
    $data .= trim($line)."\n"; 
} //end while 
//avoiding problems with data that includes "\r" 
$data = str_replace("\r", "", $data); 
//if empty query 
if ($data == "") { 
    $data = "\nno matching records found\n"; 
} 
$count = $result->field_count; 

//Download csv file 
header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=FILENAME.csv"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 
echo $header."\n".$data."\n"; 

} 
?> 

打造“class.php”的文件,在这个例子之后,使用该功能上“的download.php”文件:

<?php 
//call the "class.php" file 
require_once 'class.php'; 
//instantiate DB class 
$export = new DB(); 
//call function 
$export->downloadCsv(); 
?> 

下载后,用MS Excel打开文件。

我希望这对你有帮助,我认为我写得很好,对于文本和代码字段我感觉不太舒服。