我正在尝试使用 XMLWriter 在PHP中创建和编写 XML 文件。
我的代码如下:
$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();
这似乎在屏幕上创建了有效的XML
<?xml version="1.0" encoding="UTF-8"?>
<items>
<main>
<user_id>3</user_id>
<msg_count>11</msg_count>
</main>
<msg category="test"/>
</items>
但是,当我尝试使用:
回显XML时echo $writer->outputMemory();
除非使用以下命令创建XML文件,否则输出为空白
$filename = "xml/example.xml";
$file = $writer->outputMemory();
file_put_contents($filename,$file);
文件内容也是空白的。
我如何将XML输出到文件中? outputMemory()
函数似乎没有填充。
答案 0 :(得分:1)
您可以尝试使用该代码
$filename = "xml/example.xml";
header("Content-Type: text/html/force-download");
header("Content-Disposition: attachment; filename=".$filename.".xml");
并且不再使用:
$filename = "xml/example.xml";
$file = $writer->outputMemory();
file_put_contents($filename,$file);
Pd:对不起,我的英语不好。