有没有办法在 php 中将字符串作为文件句柄访问?
我所在的服务器仅限于 PHP 5.2.6,这意味着 str_getcsv 对我不可用。我使用的是 fgetcsv,它需要“指向由 fopen()、popen() 或 fsockopen() 成功打开的文件的有效文件指针”。进行操作。
我的问题是:有没有办法将字符串作为文件句柄访问?
我的另一个选择是将字符串写入文本文件,然后通过 fopen()
访问它,然后使用 fgetcsv
,但我希望有一种方法可以做到直接执行此操作,就像在 Perl 中一样。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您查看手册页上的用户注释
str_getcsv
,你会发现这个丹尼尔的注释,它提出了这个函数(引用):它似乎完全按照您的要求进行:它使用一个流,该流指向内存中的临时文件句柄,以使用
fgetcsv
就可以了。请参阅 PHP 输入/输出流,了解有关
php://temp
流包装器。当然,您应该测试它是否适合您 - 但是,至少,这应该让您了解如何实现这一目标;-)
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) :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 ;-)
我很震惊没有人回答这个解决方案:
并且内存饥饿的完美解决方案:
?>
I'm horrified that no one has answered this solution:
And memory hungry perfect solution:
?>
为了回答您的一般问题,是的,您可以将变量视为文件流。
http://www.php.net/manual/en/function .stream-context-create.php
以下是 PHP 手册上一些不同评论的复制和粘贴(因此我不能保证它的生产准备程度):
当然,对于您的特定示例,有是可以使用的更简单的流方法。
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):
Of course, for your particular example, there are simpler stream methods that can be used.
您可以使用 php://memory 等流句柄来实现您的目的正在追赶。只需打开、fwrite、倒带,您就应该能够使用 fgetcsv。
You can use stream handles such as php://memory to achieve what you're after. Just open, fwrite, rewind, and you should be able to use fgetcsv.
不幸的是,这是不可能的。您不能将字符串视为文件中的流。您确实必须首先将字符串写入文件,然后使用
fopen
打开该文件。现在最明显的部分是,您考虑过升级吗?
Unfortunately, that is not possible. You cannot treat a string as if it's a stream from a file. You would indeed have to first write the string to a file, and then open said file using
fopen
.And now for the obvious part, have you considered upgrading?