有没有办法在 php 中将字符串作为文件句柄访问?

发布于 2024-08-21 14:16:03 字数 274 浏览 4 评论 0原文

我所在的服务器仅限于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

紅太極 2024-08-28 14:16:03

如果您查看手册页上的用户注释 str_getcsv,你会发现这个丹尼尔的注释,它提出了这个函数(引用)

<?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;
    }
}
?>

它似乎完全按照您的要求进行:它使用一个流,该流指向内存中的临时文件句柄,以使用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) :

<?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 ;-)

芯好空 2024-08-28 14:16:03

我很震惊没有人回答这个解决方案:

<?php

$string = "I tried, honestly!";
$fp     = fopen('data://text/plain,' . $string,'r');

echo stream_get_contents($fp);

#fputcsv($fp, .......);

?>

并且内存饥饿的完美解决方案:

<?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, .......);

?>

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, .......);

?>

北方。的韩爷 2024-08-28 14:16:03

为了回答您的一般问题,是的,您可以将变量视为文件流。

http://www.php.net/manual/en/function .stream-context-create.php

以下是 PHP 手册上一些不同评论的复制和粘贴(因此我不能保证它的生产准备程度):

<?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);
}
?>

当然,对于您的特定示例,有是可以使用的更简单的流方法。

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.

浅语花开 2024-08-28 14:16:03

您可以使用 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.

单调的奢华 2024-08-28 14:16:03

不幸的是,这是不可能的。您不能将字符串视为文件中的流。您确实必须首先将字符串写入文件,然后使用 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文