【问题标题】:PHP not creating downloadable CSV filePHP没有创建可下载的CSV文件
【发布时间】:2013-11-22 11:47:36
【问题描述】:

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

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;

【问题讨论】:

    标签: php mysql csv mysqli


    【解决方案1】:
    1. 检查 phpinfo 是否启用了 mysqli 扩展。

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

    还请注意,您丢失了检索到的第一条记录的日期,因为您调用了:

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

    分别

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

    【讨论】:

    • 我已经注释掉了标头调用,当我运行我的代码时没有任何反应,即没有数据显示
    • 也检查您的服务器日志。除非您忘记粘贴上面的代码,否则您的代码最后会缺少一个 }(关闭 else of if (mysqli_connect_errno())。
    【解决方案2】:

    什么不工作?

    你有什么错误吗?

    文件是空的吗,有文件下载吗?

    可能错误未启用,试试这个:

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

    【讨论】:

    • 通过 ssh 连接,然后尝试这个命令:tail -f [PATH TO ERROR LOG] 在 Ubuntu 上:tail -f /var/log/mysql.err 然后尝试再次打开你的脚本,看看是否有任何错误。
    • 我刚刚意识到我忘了关闭我的 else 语句。当我现在运行代码时,它显示“无数据”
    • 那么错误就在这里:mysqli_num_rows($result) == 0。你确定,你得到任何结果吗? “bodyshops_master_network”是真名还是bodyshops-master-network(
    【解决方案3】:

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

    我一直在寻找一种简单的方法来使用 mysqli 并下载一个 csv 文件,该文件可以由 excel 读取而不会出现 UTF-8 问题(使用 ñ,á,ü...)。我没有找到它,所以我自己创建了一个(从 Google 和 StackOverflow 的答案中学习),几个小时后我终于得到了一些有用的东西。

    这是一个连接数据库的类,函数将使用 mysqli 和 PHP 做任何你想做的事情。在这种情况下,调用这个类(需要或包含),只需使用“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打开文件。

    希望对你有帮助,我觉得我写的不错,对文本和代码字段感觉不太舒服。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多