0

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.'

Martin Burch
  • 2,726
  • 4
  • 31
  • 59

1 Answers1

2

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

Guillaume Sainthillier
  • 1,655
  • 1
  • 9
  • 13
  • Thanks! A real temporary file seems like the only solution. Could you explain more about `tempnam()`? It looked like a typo but I see it is a real PHP function! – Martin Burch Mar 03 '17 at 17:49
  • 1
    tempnam() function just create a uniq file into the directory passed in the first argument. It also returns the filename including the path so you're ready to work with this ! – Guillaume Sainthillier Mar 03 '17 at 17:51