I'm on a server where I'm limited to PHP 5.2.6 which means str_getcsv is not available to me. I'm using, instead fgetcsv which requires "A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()." to operate on.
My question is this: is there a way to access a string as a file handle?
My other option is to write the string out to a text file and then access it via fopen()
and then use fgetcsv
, but I'm hoping there's a way to do this directly, like in perl.
I'm horrified that no one has answered this solution:
<?php
$string = "I tried, honestly!";
$fp = fopen('data://text/plain,' . $string,'r');
echo stream_get_contents($fp);
#fputcsv($fp, .......);
?>
And memory hungry perfect solution:
<?php
class StringStream
{
private $Variable = NULL;
protected $fp = 0;
final public function __construct(&$String, $Mode = 'r')
{
$this->$Variable = &$String;
switch($Mode)
{
case 'r':
case 'r+':
$this->fp = fopen('php://memory','r+');
fwrite($this->fp, @strval($String));
rewind($this->fp);
break;
case 'a':
case 'a+':
$this->fp = fopen('php://memory','r+');
fwrite($this->fp, @strval($String));
break;
default:
$this->fp = fopen('php://memory',$Mode);
}
}
final public function flush()
{
# Update variable
$this->Variable = stream_get_contents($this->fp);
}
final public function __destruct()
{
# Update variable on destruction;
$this->Variable = stream_get_contents($this->fp);
}
public function __get($name)
{
switch($name)
{
case 'fp': return $fp;
default: trigger error('Undefined property: ('.$name.').');
}
return NULL;
}
}
$string = 'Some bad-ass string';
$stream = new StringStream($string);
echo stream_get_contents($stream->fp);
#fputcsv($stream->fp, .......);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With