繁体   English   中英

使用 XMLWriter 在 PHP 中生成 XML 文件 - outputMemory() 函数不起作用

[英]Using XMLWriter to generate XML File in PHP - outputMemory() function not working

我正在尝试使用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()函数似乎没有被填充。

你可以试试那个代码

$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:对不起,我的英语不好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM