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

Author: Azat

Techies, entrepreneur, 20+ years in tech/IT/software/web development expert: NodeJS, JavaScript, MongoDB, Ruby on Rails, PHP, SQL, HTML, CSS. 500 Startups (batch Fall 2011) alumnus. http://azat.co http://github.com/azat-co

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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.