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.
openURI("xml/example.xml")?