无法弄清楚如何使用DOM保存新输出的文档


Can not figure out how to save the new outputed document with DOM

使用以下脚本,我通过XML的XSLT重命名元素并输出结果。但是我想将其保存在浏览器上的新文件中,但我唯一能做的就是保存输入 XML。

<?php
// create an XSLT processor and load the stylesheet as a DOM 
$xproc = new XsltProcessor();
$xslt = new DomDocument;
$xslt->load('stylesheet.xslt');    // this contains the code from above
$xproc->importStylesheet($xslt);

// your DOM or the source XML (copied from your question)
$xml = '<document><item><title>Hide your heart</title><quantity>1</quantity><price>9.90</price></item></document>';
$dom = new DomDocument;
$dom->loadXML($xml);
// do the transformation
if ($xml_output = $xproc->transformToXML($dom)) {
    echo $xml_output;
} else {
    trigger_error('Oops, XSLT transformation failed!', E_USER_ERROR);
} 
?>

我用了

echo $dom->saveXML();
$dom->save("write.xml")

并用没有运气的xml_output代替了它。

if ($xml_output = $xproc->transformToDoc($dom)) {
  $xml_output->save('write.xml');
} else {
  trigger_error('Oops, XSLT transformation failed!', E_USER_ERROR);
}

transformToXML()返回一个字符串而不是一个DOMDocument。您还可以使用常见的文件处理函数将字符串写入文件

if ($xml_output = $xproc->transformToXML($dom)) {
  echo $xml_output;
  file_put_contents('write.xml', $xml_output);
} else {
  trigger_error('Oops, XSLT transformation failed!', E_USER_ERROR);
} 

更新:刚刚找到了第三种方法:)根据您想要实现的目标,这是您正在寻找的那个

$xproc->transformToURI($doc, 'write.xml');

http://php.net/xsltprocessor.transformtouri

您可以在手册中找到整个班级的签名:http://php.net/class.xsltprocessor