Force Download Dialog on XML (or any other) File Type

Strangely, but Chrome browser doesn’t have build-in support to display XML in a pretty and colored format with expandable and collapsible pluses and minuses and indentation the way it’s in FF and IE.
Of course there are plug-ins but for regular users opening link with XML file brings inconsistent results: in FF and IE they see nicely formatted XML and in Chrome they see just plain text.
One of the solution is to force download dialog on opening the link.

We can do it by:

  • adding rules to htaccess
  • creating intermediate PHP (or any other) script which reads and outputs content of out XML file

First approach utilize changing MIME header type form XML which browser will try to display to something else (usually applicaton/octet-stream); second uses ‘Content-Disposition: attachment;’.
Here is the code for .htaccess file

<Files *.xml>
ForceType applicaton/octet-stream
</Files>

or if you want to apply it only to specific folder

<Directory /home/web/public/htdocs/doc>
<Files ~ *.xml>
ForceType applicaton/octet-stream
</Files>
</Directory>

This approach is not very consistent in IE.

Second approach is better because as it uses Content-Disposition and provides robust consistency in browsers:

<?php
header('Content-Type: text/xml');
header('Content-Length: 202');
header('Content-Disposition: attachment;filename="test.xml"');
$fp=fopen('xmlv.xml','r');
fpassthru($fp);
fclose($fp);
?>

I also read that following code for htaccess might work but I haven’t tested it:

AddType application/octet-stream .xml mov .mp3 .zip

--
Best Regards,
Azat Mardan
Microsoft MVP | Book and Course Author | Software Engineering Leader
Azat Mardan avatar
https://www.linkedin.com/in/azatm
To contact Azat, the main author of this blog, submit the contact form or schedule a call at clarity.fm/azat and we can go over your bugs, questions and career.

One thought on “Force Download Dialog on XML (or any other) File Type

Leave a Reply

Your email address will not be published. Required fields are marked *