How to use PhpSpreadsheet with App Engine and Google Cloud Storage
Solution 1:
Here's a working sample code:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Google\Cloud\Storage\StorageClient;
$bucketName = 'BUCKET_NAME'; // Name of the GCS bucket
$objectName = 'FILENAME.xlsx'; // Name of the new file we are creating
try {
$storage = new StorageClient();
$storage->registerStreamWrapper();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$sheet->setCellValue('B1', 'Hello You !');
$writer = new Xlsx($spreadsheet);
ob_start();
$writer->save('php://output');
$content = ob_get_contents();
ob_end_clean();
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($content, [
'name' => $objectName
]);
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
Below are screenshots of the spreadsheets with content in the Google Cloud Storage:
In PHP, there is a reference called PHP Output Control.
I used ob_start()
to create an output buffer and ob_end_clean()
to delete the topmost output buffer and all of its contents without sending anything to the browser.
I also used php://output
to store the file temporarily in the script's working directory according to the PHPSpreadsheet Documentation.