4

I'm working on a PostgreSQL to XML converter. Which should extract the values of different Tables. The relevant code below:

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->startDocument();

    $query = new data_DataBaseQuery();
        $xml->startElement();
     .......
        $xml->endElement();

And if I use echo htmlentities($xml->outputMemory()); I get as output what I want. But I'd like to make the exported file donwloadable with a specicic name.

Can you help me at this point?

$xml->openURI('test.xml');
   ...
$xml->flush();

Doesn't work somehow. It leads me only to a empty page with the output.But if this would be the proper method, can someone explain it to me?

Thank you in advance

pguetschow
  • 5,176
  • 6
  • 32
  • 45

2 Answers2

3

If you want to create the XML document on the fly offering the download it's a combination of sending the correct HTTP response headers and making XMLWriter write to standard output:

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

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->setIndent(true);
$writer->startDocument();

$query = new DataBaseQuery();
$writer->startElement();
# ...
$writer->endElement();

# ...

$writer->endDocument();
$writer->flush();

This should make the browser display the XML file - this is so that you can easily verify creating the XML worked.

To make it offering the download dialog, you have to specify an additional second header:

header('Content-type: text/xml');
header('Content-Disposition: attachment; filename=example.xml');

# ...

References:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
1

You can output the content in a file with the openURI() method. And after that you will be able to download it. Use it instead of openMemory().

$xml = new XMLWriter();

$xml->openURI("test.xml");

$xml->setIndent(true);
$xml->startDocument();

$query = new data_DataBaseQuery();
    $xml->startElement();
 .......
    $xml->endElement();

$xml->flush();
BernatL
  • 72
  • 10
  • Thank you but now I get an error: `failed to open stream: Read-only file system(2)` . How do I solve this? And I think you forgot `$xml->openMemory(); `? – pguetschow Aug 18 '15 at 09:41
  • The method `XMLWriter::openMemory()` is intended for using memory for string output, if you want to write it on file you don't have to use it. Check for file existance and give write permissions to Apache on the directory. – BernatL Aug 18 '15 at 10:05
  • Okay, I found the problem. – pguetschow Aug 18 '15 at 10:24