how to download php string when button is clicked

602 views Asked by At

I have read most of the SO questions related to this and I understand that I can use following to download a string as a file in PHP:

header('Content-Disposition: attachment; filename="default-filename.txt"');
echo 'string to download';

However my problem is a bit more. I have something like following:

$csvString = "";
foreach($array as $key => $value)
{
  echo "<div> $key has $value</div>";
  $csvString = "$key,$value\n";
}
echo "<button> Click here to download as CSV</button>";

As you might have already guessed, I want $csvString to be downloaded when the button is clicked. Any pointers on how I can get that done.

1

There are 1 answers

0
venca On

Lets say you have csv.php file, then do:

if (isset($_GET['download'] == 1)) {
    header('Content-Disposition: attachment; filename="default-filename.txt"');
    foreach($array as $key => $value) {
        echo "$key,$value\n";
    }
    exit;
}

foreach($array as $key => $value) {
    echo "<div> $key has $value</div>";
}

echo "<a href='csv.php?download=1'><button> Click here to download as CSV</button></a>";

Basically, if you want all the logic in single file, first check if download is requested and if so prepare it. If no download is request just write your html.