Can not figure out how to save the new outputed document with DOM
With the following script I rename the elements through XSLT of an XML and output the result. However I want to save it in a new file on my browser but the only I managed to do is to save the input 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-&开发者_如何学Cgt;transformToXML($dom)) {
echo $xml_output;
} else {
trigger_error('Oops, XSLT transformation failed!', E_USER_ERROR);
}
?>
I used
echo $dom->saveXML();
$dom->save("write.xml")
and replaced it with xml_output
with no luck.
if ($xml_output = $xproc->transformToDoc($dom)) {
$xml_output->save('write.xml');
} else {
trigger_error('Oops, XSLT transformation failed!', E_USER_ERROR);
}
transformToXML()
returns a string instead of a DOMDocument
. You can also write the string to a file using the common file handling functions
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);
}
Update: Just found the third method :) Depending on what you want to achieve this is the one you are looking for
$xproc->transformToURI($doc, 'write.xml');
http://php.net/xsltprocessor.transformtouri
You can find the signature of the whole class at the manual: http://php.net/class.xsltprocessor
精彩评论