有没有办法访问一个字符串作为文件句柄在PHP? [英] Is there a way to access a string as a filehandle in php?
问题描述
我在一个服务器上,我只限于PHP 5.2.6,这意味着str_getcsv不可用于我。我使用,而不是fgetcsv,它要求一个有效的文件指针,成功打开由fopen(),popen()或fsockopen()的文件。
我的问题是:有没有办法访问一个字符串作为文件句柄?
我的其他选项是将字符串写入文本文件,然后通过 fopen()
然后使用 fgetcsv
,但我希望有一种方法可以直接这样做,像perl。
如果您查看 str_getcsv
,您会看到来自daniel的此笔记,其提出此功能(引用)
<?php
if(!function_exists('str_getcsv')){
function str_getcsv($ input,$ delimiter =,,$ enclosure ='',$ escape =\\){
$ fiveMBs = 5 * 1024 * 1024;
$ fp = fopen(php:// temp / maxmemory:$ fiveMBs ,'r +');
fputs($ fp,$ input);
rewind($ fp);
$ data = fgetcsv($ fp,1000,$ delimiter, $ enclosure); // $ escape仅在5.3.0中添加
fclose($ fp);
return $ data;
}
}
?>
它似乎在做你所要求的:它使用一个流,文件句柄在内存中使用 fgetcsv
。 p>
请参阅 PHP输入/输出流,其中包括 php:// temp
流包装器。
当然,你应该测试一下它能正常工作,但至少应该告诉你如何实现这一点; - )
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.
If you take a look in the user notes on the manual page for str_getcsv
, you'll find this note from daniel, which proposes this function (quoting) :
<?php
if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
$fiveMBs = 5 * 1024 * 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
fputs($fp, $input);
rewind($fp);
$data = fgetcsv($fp, 1000, $delimiter, $enclosure); // $escape only got added in 5.3.0
fclose($fp);
return $data;
}
}
?>
It seems to be doing exactly what you asked for : it uses a stream, which points to a temporary filehandle in memory, to use fgetcsv
on it.
See PHP input/output streams for the documentation about, amongst others, the php://temp
stream wrapper.
Of course, you should test that it works OK for you -- but, at least, this should give you an idea of how to achieve this ;-)
这篇关于有没有办法访问一个字符串作为文件句柄在PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!