Phpspreadsheet: Get a resource from Writers for PSR-7 integration

Created on 18 Oct 2016  Â·  12Comments  Â·  Source: PHPOffice/PhpSpreadsheet

Hi there,

I want to suggest a feature for the Writers. Not easy to implement if I trust the current codebase, but pretty helpful for many integrations.

Modern PSR-7 frameworks needs to work with, well, PSR-7 Response objects. These objects use Stream objects that rely on resources to fetch data.

In the current version of PhpSpreadsheet, it's only possible to write on a file or php://output / php://stdout. It's quite tricky to get a resource this way, and writing to a temporary file could not be a viable option on many application architecture.

Adding an abstract getResource method to BaseWriters would be a great improvement for PSR-7 frameworks integration.

enhancement help wanted stale

Most helpful comment

If the file is large. It's best not to use file_get_contents().

@jbelien

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use GuzzleHttp\Psr7\Response;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExportXlsxHandler implements RequestHandlerInterface {

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $file = tempnam(File::sysGetTempDir(), 'phpxltmp');
        $writer = new Xlsx($spreadsheet);
        $writer->save($file);

        return new class($file, $filename) extends Response {
            private $file;

            public function __construct($file, $filename)
            {
                $this->file = $file;
                parent::__construct(
                    200,
                    [
                        'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        'Content-Disposition' => "attachment;filename=\"{$filename}.xlsx\"",
                        'Cache-Control' => 'max-age=0',
                    ],
                    fopen($file, 'r+')
                );
            }

            public function __destruct()
            {
                @unlink($this->file);
            }
        };
    }
}

All 12 comments

I am not familiar with the details of PSR-7 yet, and can't find much related to "resource" in the spec. Would you care to detail what you had in mind ? Would it be an implementation of Psr\Http\Message\ResponseInterface ? or usage of that interface ?

Hi, and sorry I probably wasn't clear. The resource isn't at all part of PSR-7 specs, I was talking about the PHP resource type : http://php.net/manual/en/language.types.resource.php

In this case, it will be a stream resource. What could be a great add to PhpSpreadsheet is to provide a getResource method that returns the stream resource of the current document. If document is provided by stream, it's still possible to use a php://memory stream, for example.

Behing able to retrieve this resource will be really useful especially for PSR-7 integration (PSR-7 Responses need a PHP resource to generate a response body).

My take on this would be to modify the signature of PhpOffice\PhpSpreadsheet\Writer\IWriter::save() to always return the file descriptor of the written file. Then it's up to you to do whatever you need with that file descriptor. The save() method already supports writing to php://output (via temp files for some writers), so we only need to add support for php://memory, which should not be too difficult hopefully.

This would be for convenience only and would not bring any gain of performance, because we would still be creating temp files on disk.

So usages would be something like:

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

$writer->save('/some/path/to/file.xlsx'); // standard, save to disk
$writer->save('php://output');            // to download the file in the browser
$handle = $writer->save('php://memory');  // to get a file descriptor to the stream in memory

Would this solve your use case ?

Hi, and thanks for your reply. It will totally solve my case.

If you want to create a PR for that, it would be best to modify all writer, and unit test the new feature.

Otherwise I am not sure when we're gonna have time for it, since we are more busy with refactoring things, rather than adding new features for the time being.

Sure, I'll take a look at this. I can't say when for now, but if I manage
to find a few hours I'll send a PR.

2016-11-27 18:03 GMT+01:00 Adrien Crivelli notifications@github.com:

If you want to create a PR for that, it would be best to modify all
writer, and unit test the new feature.

Otherwise I am not sure when we're gonna have time for it, since we are
more busy with refactoring things, rather than adding new features for the
time being.

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/PHPOffice/PhpSpreadsheet/issues/28#issuecomment-263133602,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAIGZcc6ujPVMcR-uvLS_JDkfpEk0SQeks5rCbfTgaJpZM4KaJY_
.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
If this is still an issue for you, please try to help by debugging it further and sharing your results.
Thank you for your contributions.

Hello everyone,

Same issue as mentioned by @lucascorbeaux : I want to be able to use PSR-7 Response object.
It would be really awesome to implement php://memory in save() function like mentioned by @PowerKiKi :

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$handle = $writer->save('php://memory'); // to get a file descriptor to the stream in memory

Meanwhile, if anyone else needs it, here is how I did it using Zend Framework :

    $file = 'phpxltmp.xlsx';

    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save($file);

    $body = new \Zend\Diactoros\Stream('php://temp', 'w+');
    $body->write(file_get_contents($file));

    unlink($file);

    $response = new \Zend\Diactoros\Response($body));

I mentioned in another issue that an important blocking factor is that ZipArchive does not work with resources. So to implement this properly would mean to replace ZipArchive with something else. It could be a non-trivial work, but it could be worth the effort if it means we can then avoid touching the disk entirely... PR welcome...

I never used it (I'll have a look) but seems that ZipStream-PHP could be a solution to replace ZipArchive.

If the file is large. It's best not to use file_get_contents().

@jbelien

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use GuzzleHttp\Psr7\Response;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExportXlsxHandler implements RequestHandlerInterface {

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $file = tempnam(File::sysGetTempDir(), 'phpxltmp');
        $writer = new Xlsx($spreadsheet);
        $writer->save($file);

        return new class($file, $filename) extends Response {
            private $file;

            public function __construct($file, $filename)
            {
                $this->file = $file;
                parent::__construct(
                    200,
                    [
                        'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        'Content-Disposition' => "attachment;filename=\"{$filename}.xlsx\"",
                        'Cache-Control' => 'max-age=0',
                    ],
                    fopen($file, 'r+')
                );
            }

            public function __destruct()
            {
                @unlink($this->file);
            }
        };
    }
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

smartlara picture smartlara  Â·  5Comments

isopen picture isopen  Â·  3Comments

PowerKiKi picture PowerKiKi  Â·  4Comments

ionesculiviucristian picture ionesculiviucristian  Â·  4Comments

garnold picture garnold  Â·  5Comments