How to download a temporary file

后端 未结 4 1354
执念已碎
执念已碎 2021-02-05 05:49

I\'m trying to create a short PHP script that takes a JSON string, converts it to CSV format (using fputcsv), and makes that CSV available as a downloaded .csv file

相关标签:
4条回答
  • 2021-02-05 06:04

    json_decode() by default translates elements into objects rather than arrays. fputcsv() expects the data passed to be an array.

    I'd recommend changing:

    $jsonArray = json_decode( $_POST['json'] );
    

    To:

    $jsonArray = json_decode( $_POST['json'], True );
    

    And see if that doesn't fix your problem.

    When attempting to tackle problems such as these I'd highly recommend enabling display_errors and setting error_reporting to E_ALL to see if there some sort of error you are missing out on:

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    
    // Rest of your code here
    
    0 讨论(0)
  • 2021-02-05 06:11

    One problem is that tmpfile() returns a file handle, while filesize takes a filename as parameter.
    The following line:

    header('Content-Length: ' . filesize($tmp));
    

    probably gets evaluated as:

    header('Content-Length: 0');
    

    Check that all the calls to header() are executed before any output happens.

    0 讨论(0)
  • 2021-02-05 06:15

    Note that tmpfile() returns a file handle, but all the functions you have need a file path (i.e a string), not a handle - notably basename, filesize, and readfile. So none of those function calls will work correctly. Also basename won't return a file extension either. Just call it whatever you want, i.e

    'Content-Disposition: attachment; filename=data.csv'
    

    As @Joshua Burns also says, make sure you're passing in an array to fputcsv or use the assoc parameter.

    0 讨论(0)
  • 2021-02-05 06:20

    Firstly, check this string out, i would change it to:

    header('Content-Disposition: attachment; filename="'.basename($tmp).'"');
    

    i had the problem with it once, with browser compatibility :)

    0 讨论(0)
提交回复
热议问题