0

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.

3
  • 1
    <a href="download.php?id=whatever">click here</a> Commented Jun 18, 2015 at 14:09
  • @MarcB erm....how does that work? Commented Jun 18, 2015 at 14:10
  • @UndefinedVariable I think, this tutorial will help you. Commented Jun 18, 2015 at 18:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.