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

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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();

3 Comments

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(); ?
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.
Okay, I found the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.