Search code examples
phpfileobject

PHP: Is it possible to create a SplFileObject object from file contents (string)?


For example:

$contents = file_get_contents(image.png);

Is it possible to create a SplFileObject object from $contents?

Thanks!


Solution

  • PHP has some special stream wrappers that let you re purpose the various file system functions:

    $contents = 'i am a string';
    $file = 'php://memory'; // full memory buffering mode
    //$file = 'php://temp/maxmemory:1048576'; //partial memory buffering mode. Tries to use memory, but over 1MB will automatically page the excess to a file.
    $o = new SplFileObject($file, 'w+');
    $o->fwrite($contents);
    
    // read the value back:
    $o->rewind();
    $o->fread(); // 'i am a string'
    

    You don't need to use SplFileObject to use those wrappers though; you could use fopen and fwrite instead.