1

I am trying to create and write an XML file in PHP using XMLWriter.

My code is as follows:

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument('1.0','UTF-8');
$writer->setIndent(4);
$writer->startElement('items');
$writer->startElement("main");
$writer->writeElement('user_id', 3);
$writer->writeElement('msg_count', 11);
$writer->endElement();
$writer->startElement("msg");
$writer->writeAttribute('category', 'test');
$writer->endElement();
$writer->endElement();
$writer->endDocument();
$writer->flush();

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

echo $writer->outputMemory();

This seems to create valid XML onscreen

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <main>
    <user_id>3</user_id>
    <msg_count>11</msg_count>
  </main>
  <msg category="test"/>
</items>

However when I try to echo the XML using:

echo $writer->outputMemory();

The output is blank, additionally when the XML file is created using:

$filename = "xml/example.xml";
$file = $writer->outputMemory();
file_put_contents($filename,$file);

The file contents are also blank.

How I am able to output the XML to the file? The outputMemory() function doesn't seem to be getting populated.

2
  • What if you do openURI("xml/example.xml") ? Commented Feb 6, 2017 at 9:09
  • No joy unfortunately, I am pulling my hair out. Commented Feb 6, 2017 at 11:51

1 Answer 1

2

you can try with that code

$filename = "xml/example.xml";
header("Content-Type: text/html/force-download");
header("Content-Disposition: attachment; filename=".$filename.".xml");

and no longer use:

$filename = "xml/example.xml";
$file = $writer->outputMemory();
file_put_contents($filename,$file);

Pd: Sorry for my bad english.

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

Comments

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.