donglvlao8367 2016-10-08 12:29
浏览 36

使用PHP标头下载PHP文件

I have a function that basically on user request gets the data from the database exports it to csv file and then automatically downloads that csv file for the user. The function works as I expected however for some reason when the file that gets downloaded to the users computer it has some random html data in it. I am not sure how this is getting added to the file as I check the file that gets created on the server and there is no random text within it. Below is the function that I am using:

private function _exporte() 
{
    $file_name = "/path-". date('d-m-Y') .".csv";

    if(file_exists($file_name) == TRUE) 
        unlink($file_name);

    $file = fopen($file_name, 'w') or die ("Can not open file to write");

    $file_vars = array();

    $data = $this->name_model->get_data();

    $headerDisplayed = false;

    foreach($data as $row)
    {
        $file_vars['Code'] = $row['code'];
        $file_vars['Category'] = $row['category'];
        $file_vars['Category ID'] = $row['category_id'];

        if(!$headerDisplayed)
            fputcsv($file, array_keys($file_vars));

        $headerDisplayed = true;

        fputcsv($file, array_values($file_vars));
    }

    if (file_exists($file_name)) 
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file_name));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file_name));
        readfile($file_name);
    }
}

I have added image of the csv file for reference. enter image description here

  • 写回答

1条回答 默认 最新

  • dongzheng8463 2016-10-08 12:35
    关注

    you can use a function like bellow for download image:

    function getLogo($path_to_your_file)
        {        
          header("Content-Type: image/jpeg");
          return file_get_contents($path_to_your_file);
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测