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

前端 未结 5 1998
遥遥无期
遥遥无期 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:20

    I'm horrified that no one has answered this solution:

    
    

    And memory hungry perfect solution:

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

    ?>

提交回复
热议问题