5

Possible Duplicate:
Forcing to download a file using PHP

If I have a json in a variable, how can I force the download? (The file not exist).

Thanks.

Community
  • 1
  • 1
keepyourweb
  • 664
  • 4
  • 10
  • 19

2 Answers2

32
header('Content-disposition: attachment; filename=file.json');
header('Content-type: application/json');
echo $json;
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • @keepyourweb: Yes, and? Did you try this? What happened? – gen_Eric Jul 18 '12 at 16:20
  • I make an ajax call where I spend a json, and I would force the download with php. Before I don't specified that I do an ajax call because I thought that it changed nothing. – keepyourweb Jul 18 '12 at 16:27
  • 1
    @keepyourweb: That changes everything. You can't force a download from an AJAX call. You need to submit the form normally, or something. For the file to be downloaded to the client's PC, the browser needs to actually go to the page. – gen_Eric Jul 18 '12 at 18:25
2
$json = json_encode( array( 'test' => 'test' ));

header('Content-disposition: attachment; filename=jsonFile.json');
header('Content-type: application/json');

echo( $json);
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
  • 1
    And...? If you have that code in a page, and you visit that page in your browser, you should get a file download prompt to pop up. Do you mean something else by 'force download'? – Jeff Lambert Jul 18 '12 at 16:17
  • I make an ajax call where I spend a json, and I would force the download with php. Before I don't specified that I do an ajax call because I thought that it changed nothing. – keepyourweb Jul 18 '12 at 16:27