4

Basically I wrote a script that generates a xml file based on user input. After the file is generated a download link appears like so:

<a href="path/to/file.xml">Download File</a>

But when clicked it opens the xml in the browser, I want it to start downloading when the link it clicked instead. Is there any way to achieve that?

Magpue
  • 53
  • 1
  • 4
  • 1
    possible duplicate of [Forcing to download a file using PHP](http://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php) – Pekka Oct 01 '10 at 17:27

5 Answers5

6

Yeah, there is. It does require specifying some headers. Exactly how it works depends on what language you're using, but here's an example using php, taken off of php.net:

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

Basically, first we tell the client what type of file we're sending, then we tell the client that what we're sending is an attachment, and it's name, instead of it being a page to display, and then finally we print/read the file to the output.

Given that you're already using php to generate the xml file, I would suggest adding the header commands above to the code that generates the xml file, and see if that does the trick.

John Fiala
  • 4,561
  • 3
  • 30
  • 26
  • 1
    One note: in your link, make sure to do `target="_blank"` so that IE opens it in a new window, otherwise IE won't know what to do with it (We've had problems in IE6 and 7 that this solved)... – ircmaxell Oct 01 '10 at 17:33
1

If you happen to be using Apache for your web server, and you always want to force downloading of XML files, there is a more efficient way to do what @chigley suggested. Just add the following to a .htaccess file.

<Files *.xml>
ForceType application/xml
Header set Content-Disposition attachment
</Files>
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
0

What happens when a browser sees a link is not dependent on the link, but rather on the target of the link. Your web server should send the appropriate header: Content-Disposition: attachment;filename="file.xml" to tell the browser that it should prompt to save the file instead of displaying it.

Yuliy
  • 17,381
  • 6
  • 41
  • 47
0

It depends on what the client computer does with XML files. If you doubleclick on a XML file, it will open in your browser probably.

hsmit
  • 3,906
  • 7
  • 34
  • 46
0

download.php:

header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="file.xml"');
readfile('/path/to/file.xml');

HTML:

<a href="download.php">Download</a>
chigley
  • 2,562
  • 20
  • 18