Is there a way to access a string as a filehandle in php?

前端 未结 5 2024
遥遥无期
遥遥无期 2020-12-17 17:22

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 s

5条回答
  •  清酒与你
    2020-12-17 18:10

    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):

    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 "

    $num fields in line $row:

    \n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "
    \n"; } } fclose($handle); } ?>

    Of course, for your particular example, there are simpler stream methods that can be used.

提交回复
热议问题