Search code examples
phpxmlajaxxmldom

How to save an XML file to local file system (client) in PHP?


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.


Solution

  • 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?