Search code examples
phpphp-stream-wrappers

Provide a file handle to a PHP function expecting a file path


Using PHPExcel, I would like to read a file from the internet. The PHPExcel library seems suited to opening only local files, not URLs. Here's what I tried:

<?php
require __DIR__ . '/vendor/autoload.php';
$string = file_get_contents('http://opendatakit.org/wp-content/uploads/static/sample.xls');

$stream = fopen('php://memory','r+');
fwrite($stream, $string);
rewind($stream);

$objPHPExcel = PHPExcel_IOFactory::load('php://memory');

This is the error I received:

Fatal error: Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open php://memory for reading! File does not exist.'

I also tried passing the URL directly (PHPExcel_IOFactory::load('http://opendatakit.org/wp-content/uploads/static/sample.xls')). Similar error.

Fatal error: Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open http://opendatakit.org/wp-content/uploads/static/sample.xls for reading! File does not exist.'

EDIT: Also tried a temporary file

$string = file_get_contents('http://opendatakit.org/wp-content/uploads/static/sample.xls');

$temp = tmpfile();
fwrite($temp, $string);
fseek($temp, 0);

$objPHPExcel = PHPExcel_IOFactory::load($temp);

Different error this time:

Warning: pathinfo() expects parameter 1 to be string, resource given in /project/vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php on line 224

Warning: file_exists() expects parameter 1 to be a valid path, resource given in /project/vendor/phpoffice/phpexcel/Classes/PHPExcel/Reader/Excel2007.php on line 81

Fatal error: Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open Resource id #10 for reading! File does not exist.'


Solution

  • Your thinking is good. But PHPExcel needs a filepath to work correctly. You can try with this sample :

    $string = file_get_contents('http://opendatakit.org/wp-content/uploads/static/sample.xls');
    
    $tmp = tempnam(sys_get_temp_dir(), "FOO");
    file_put_contents($tmp, $string);
    
    $objPHPExcel = PHPExcel_IOFactory::load($tmp);
    
    //Perform all your operations
    // ...
    
    unlink($tmp);
    

    See PHP Manual for tempnam()