Search code examples
phpxmlxmlwriter

Output XMLWriter to XML file


I am currently using XMLWriter to display an xml file. However I would like to know how I could export the output to a .xml file.

My current code is:

$res = mysql_query($sql);

$xml = new XMLWriter();

$xml->openURI("php://output");
$xml->startDocument();
$xml->startElement('stores');

while ($row = mysql_fetch_assoc($res)) {
//loads of code
}
$xml->endElement();

$xml->flush();

Solution

  • Use a filename instead of php://output in the openURI() method.

    $writer = new XMLWriter();
    $writer->openURI('test.xml');
    $writer->startDocument("1.0");
    $writer->startElement("greeting");
    $writer->text('Hello World');
    $writer->endDocument();
    $writer->flush();