10

I currently have this

file_put_contents($tmpfile, $attachments[0]['body']);
$objPHPExcel = PHPExcel_IOFactory::load($tmpfile);

The file I am reading is extracted from an email, so rather then writing it to a tempfile I would like to read it directly into phpexcel from a string (if that makes sense)

$objPHPExcel = PHPExcel_IOFactory::load($attachments[0]['body']);

I have looked at the php excel manual but can't see how to do it, any ideas?

bumperbox
  • 10,166
  • 6
  • 43
  • 66

3 Answers3

21

This might not be the most elegant solution but here is how I solved it:

public function fromString($data=null)
{
    $file = tempnam(sys_get_temp_dir(), 'excel_');
    $handle = fopen($file, "w");
    fwrite($handle, $data);
    $return = \PHPExcel_IOFactory::load($file);
    fclose($handle);
    unlink($file);
    return $return;
}
Dieter Gribnitz
  • 5,062
  • 2
  • 41
  • 38
  • This should be marked as the correct answer since php://memory and temp cannot be reused once closed. This solution is not ideal but its the only way that PHPexcel/phpspreadsheet accepts data from a string – Avenyet Mar 05 '18 at 11:54
4

PHPExcel provides no direct method for loading from a string rather than from a file. As an alternative to actually creating a physical filesystem file for $tmpfile though, you might be able to use php://memory or php://temp

mario
  • 144,265
  • 20
  • 237
  • 291
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    Relevant issue opened in the PHPExcel issue tracker: https://github.com/PHPOffice/PHPExcel/issues/677 – CubicleSoft Sep 16 '15 at 05:38
  • How can it be done? `PHPExcel_IOFactory::load('php://temp')` seems to be wrong... Do you have any idea? Will there be any problems with zip or so? – robsch Dec 16 '15 at 12:08
  • Sorry! Could you just provide an example? I may write something to php://temp (like [here](http://php.net/manual/en/wrappers.php.php#example-351)), but how should it be passed to `PHPExcel_IOFactory::load()`. With the file pointer? – robsch Dec 16 '15 at 14:00
  • 1
    From what I can tell, a solution involving `php://memory` (and similar) is not possible, because it's not possible to pass an already open stream to PHPExcel to load from it. Passing "php://memory" as filename to PHPExcel will make it open a separate fresh stream which will be empty. – jlh Jul 20 '16 at 12:49
2

You must first create a reader for the excel file and then load that file from your constructed reader. Take a look at this for full details.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Amin Fazli
  • 152
  • 7