Use php://temp wrapper with XMLWriter
Is it possible to use the php://temp wrapper to generate an XML file with XMLWriter? I like the features it provides (memory for small files, transparent temporary file for larger output) but I can't get the syntax (if it's even possible):
<?php
header('Content-type: text/xml; charset=UTF-8');
$oXMLWriter = new XMLWriter;
$oXMLWriter->openURI('php://temp');
$oXMLWriter->开发者_StackOverflow中文版;startDocument('1.0', 'UTF-8');
$oXMLWriter->startElement('test');
$oXMLWriter->text('Hello, World!');
$oXMLWriter->endElement();
$oXMLWriter->endDocument();
// And now? *******
$oXMLWriter->flush();
I don't understand the purpose of writing to a temp file. Perhaps you want:
$oXMLWriter->openURI('php://output');
I haven't ever used XMLWriter
but it doesn't seem to take a handle to a file pointer. I think that's really what you want.
For giggles, here's something that wraps the temp interface:
class WeirdStream
{
static public $files = array();
private $fp;
public function stream_open($path)
{
$url = parse_url($path);
self::$files[$url['host']] = fopen('php://temp', 'rw');
$this->fp = &self::$files[$url['host']];
return true;
}
public function stream_write($data)
{
return fwrite($this->fp, $data);
}
}
stream_wrapper_register('weird', 'WeirdStream');
$oXMLWriter = new XMLWriter;
$oXMLWriter->openURI('weird://a');
// .. do stuff
$oXMLWriter->flush();
Now you can get at the file pointer:
$fp = WeirdStream::$files['a'];
It may be purely in memory, or it may be a temporary file on disk.
You could then loop through the data line by line:
fseek($fp, 0, SEEK_SET);
while (!feof($fp)) $line = fgets($fp);
But this is all very odd to me.
What do you need to do with the contents of php://temp
eventually? If you just need a temporary, memory-only storage, then you can use openMemory()
:
$oXMLWriter = new XMLWriter;
$oXMLWriter->openMemory();
$oXMLWriter->startDocument('1.0', 'UTF-8');
$oXMLWriter->startElement('test');
$oXMLWriter->text('Hello, World!');
$oXMLWriter->endElement();
$oXMLWriter->endDocument();
echo $oXMLWriter->outputMemory ();
精彩评论