Create PHP DOM xml file and create a save file link/prompt without writing the file to the server when headers already sent

Tags: file dom xml php

I've created a PHP DOM xml piece and saved it to a string like this:

  // create a new XML document 
  $doc = new DomDocument('1.0');
  $xmldata = $doc->saveXML();

Now I can't use the headers to send a file download prompt and I can't write the file to the server, or rather I don't want the file laying around on it.

Something like a save this file link or a download prompt would be good. How do I do it?


The same thing worked for me. But i am not using XML DOM. i use SimpleXML to parse my xml.

$xml = new SimpleXMLElement("<root></root>");

I want to give my view a custom xml which will be generated depending upon the data they give through the form. On submiting the form they get the xml as download with thier own desired name.

header('Content-type: "text/xml"; charset="utf8"');

header('Content-disposition: attachment; filename="'.$_POST['filename'].'.xml"');

echo $xml->asXML();

By : Goysar

I see from the comments that you're working from within a CMS framework and are unable to stop content from being output prior to where your code will be.

If the script in which you're working has already output content (beyond your control), then you can't do what you're trying to achieve in just one script.

Your script can either send headers saying "the following content is HTML" then output the HTML or send headers saying "the following content is XML, is an attachment and has a certain filename". You can't do both.

You can either output HTML containing a link to a separate script for downloading an XML file or you can issue a file download and output no HTML.

Therefore, you'll have to add a download link in the output of the CMS script you're modifying and then handle the download in a separate script.

I have made a working example that should help. The example includes a simple HTML document containing a download link, and a PHP script that then handles the download.

View the code below or take a look at the live example.

HTML (extraneous fluff removed, not necessarily valid)

<title>XML Download Example</title>


<a href="download.php">Download XML example</a>



// Populate XML document
    $doc = new DomDocument();
    // ... various modifications to the document are made

// Output headers
    header('Content-type: "text/xml"; charset="utf8"');
    header('Content-disposition: attachment; filename="example.xml"');

// Output content
    echo $doc->saveXML();

If you are fully unable to handle the download via a second script (perhaps you can't get access to the relevant data), you'll have to re-think the problem.

By : Jon Cram

You could enable output_buffering in your php.ini, then you might have some options with sending headers.

This video can help you solving your question :)
By: admin