【发布时间】:2017-02-06 08:58:28
【问题描述】:
我正在尝试使用 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() 函数似乎没有被填充。
【问题讨论】:
-
如果你这样做
openURI("xml/example.xml")会怎样? -
很遗憾,我正在拔头发。