PHP未创建可下载的CSV文件

PHP未创建可下载的CSV文件,php,mysql,csv,mysqli,Php,Mysql,Csv,Mysqli,我正在尝试使用php从数据库中提取数据,并将其导出到可下载的CSV文件中,该文件可以用excel打开。当我使用mysql时,我能够做到这一点。然而,许多人建议不要在我的代码中包含mysql语法,因为它已被弃用,而我应该使用mysql。我已经更改了代码,但现在我的代码不起作用。有人知道为什么吗 mysql版本(工作版本)` mysql_connect('localhost', 'xxxxx', 'xxxxx') or die('connect'); mysql_select_db('db') o

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

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;
  • 检查phpinfo以查看mysqli扩展是否已启用

  • 删除/注释标题调用,以便以纯HTML形式接收输出,以便注意是否显示了任何消息(由于死亡或编码错误),或者是否实际获得了数据

  • 还请注意,由于调用了以下命令,因此丢失了检索到的第一条记录的日期:

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

    $cols = array_keys($result->fetch_assoc()); 
    
    什么不起作用

    你有什么错误吗

    文件是否为空,是否有文件下载

    可能未启用错误,请尝试以下操作:

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

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

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

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

    例如,这将是“class.php”文件:


    我已经注释掉了标题调用,当我运行代码时,什么也没有发生,即没有显示任何数据。请检查您的服务器日志。除非您忘记粘贴上面的代码,否则您的代码末尾缺少一个}(关闭if(mysqli_connect_errno())的else)。请通过ssh连接,然后尝试以下命令:tail-f[PATH to ERROR LOG]在Ubuntu上:tail-f/var/log/mysql.err然后再次尝试打开脚本,看看是否有错误。我刚刚意识到我忘记关闭else语句。现在运行代码时,它显示“无数据”,然后错误出现在这里:mysqli_num_rows($result)==0。你确定得到了任何结果吗?是“bodyshops\u master\u network”真名或者可能是车身主网络(
    
    <?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";
    
    }
    ?>
    
    <?php
    //call the "class.php" file
    require_once 'class.php';
    //instantiate DB class
    $export = new DB();
    //call function
    $export->downloadCsv();
    ?>