【问题标题】:Using XMLWriter to generate XML File in PHP - outputMemory() function not working使用 XMLWriter 在 PHP 中生成 XML 文件 - outputMemory() 函数不起作用
【发布时间】: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") 会怎样?
  • 很遗憾,我正在拔头发。

标签: php xml xmlwriter


【解决方案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:对不起,我的英语不好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多