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?

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

4 Comments

Relevant issue opened in the PHPExcel issue tracker: github.com/PHPOffice/PHPExcel/issues/677
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?
Sorry! Could you just provide an example? I may write something to php://temp (like here), but how should it be passed to PHPExcel_IOFactory::load(). With the file pointer?
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.
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.

1 Comment

The link is dead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.