To answer your general question, yes you can treat a variable as a file stream.
http://www.php.net/manual/en/function.stream-context-create.php
The following is a copy and paste from a few different comments on the PHP manual (so I cannot vouch for how production ready it is):
<?php
class VariableStream {
private $position;
private $varname;
public function stream_open($path, $mode, $options, &$opened_path) {
$url = parse_url($path);
$this->varname = $url["host"];
$this->position = 0;
return true;
}
public function stream_read($count) {
$p=&$this->position;
$ret = substr($GLOBALS[$this->varname], $p, $count);
$p += strlen($ret);
return $ret;
}
public function stream_write($data){
$v=&$GLOBALS[$this->varname];
$l=strlen($data);
$p=&$this->position;
$v = substr($v, 0, $p) . $data . substr($v, $p += $l);
return $l;
}
public function stream_tell() {
return $this->position;
}
public function stream_eof() {
return $this->position >= strlen($GLOBALS[$this->varname]);
}
public function stream_seek($offset, $whence) {
$l=strlen(&$GLOBALS[$this->varname]);
$p=&$this->position;
switch ($whence) {
case SEEK_SET: $newPos = $offset; break;
case SEEK_CUR: $newPos = $p + $offset; break;
case SEEK_END: $newPos = $l + $offset; break;
default: return false;
}
$ret = ($newPos >=0 && $newPos <=$l);
if ($ret) $p=$newPos;
return $ret;
}
}
stream_wrapper_register("var", "VariableStream");
$csv = "foo,bar\ntest,1,2,3\n";
$row = 1;
if (($handle = fopen("var://csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Of course, for your particular example, there are simpler stream methods that can be used.