1

In my site, I have implemented the following functionality: If the user clicks on a button it triggers a PHP function which generates an XML file (that PHP function is called by AJAX). Everything is working well, but here's one thing I want to change: I don't want an .XML file to be created on the server machine; instead, I want the user to be prompted to save the .XML file locally. How do I do that? My PHP script currently looks like this:

$xml = new DOMDocument("1.0", "UTF-8");
$rootElement = $xml->appendChild($xml->createElement("SomeNodeName"));
...

// the following doesn't really work - xml doesn't get formatted :)
$xml->formatOutput = true; 

// this creates the actual file and places it on server. that's not what i need
$xml->save("MyXMLfile.xml"); 

Thanks for all the help.

Boris
  • 9,986
  • 34
  • 110
  • 147
  • 1
    This question has been asked many times here. Here's one of the better Q&A http://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php – Endophage Feb 15 '11 at 21:07
  • @Endophage: Thanks for the reference. I don't seem to find it particularly useful as I am using AJAX which is the main issue I am having - section of my page is populated with the xml content; instead I need the Save File dialog. Do you have any thoughts? Thank you. – Boris Feb 15 '11 at 21:25

1 Answers1

1

Every web content has a header, so if you specify the header for an xml file (through the use of the header() function with the appropriate code it'll work. This would mean doing something like this:

<?php
header('Content-type: text/xml');

// set the filename
header('Content-Disposition: attachment; filename="pwet.xml"');

// echo the content here
echo $xml; // simply like this, maybe?
greg0ire
  • 22,714
  • 16
  • 72
  • 101
  • Thank you for your answer. I am facing a problem with your code: the echoed $xml is displayed on a page, as instructed by AJAX. That's now what I need. I need a Save file dialog. Could you help me out? – Boris Feb 15 '11 at 21:13
  • @Boris: please read [this](http://particletree.com/notebook/ajax-file-download-or-not/), this does not seem to be possible, but you'll find a workaround in the link. – greg0ire Feb 15 '11 at 21:40