简体   繁体   中英

PHP: Read xls file from google bucket in Google app engine using php

I am using the following code but I'm getting this error:

Type: PhpOffice\PhpSpreadsheet\Reader\Exception
Code: 0
Message: File "gs://datastore/example.xls" does not exist.

My code is as follows:

$storage = new StorageClient();
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$objXLS = $reader->load("gs://datastore/example.xls");
$arrData = $objXLS->getActiveSheet()->toArray();
print "<pre>";
print_r($arrData);
print "</pre>";

The error you are getting is specifying that the file you are trying to read does not exist:

File "gs://datastore/example.xls" does not exist.

This line in your code cannot find the file you are specifying:

$objXLS = $reader->load("gs://datastore/example.xls");

To solve this, you have 2 options:

  1. To download the file from the bucket to the GAE instance, (if you are using GAE standard, this option is only valid for PHP7 )
  2. To create a wrapper so you can use the bucket as if it was the local disk.

To download the file from the bucket you will need to use downloadToFile , like this:

$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$object->downloadToFile($destination);

To use a wrapper you can use the Google Cloud Storage for PHP component . To use it, install the component and then in your code add:

require 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient();
$storage->registerStreamWrapper();  // this will create the wrapper

After this you can access files from the bucket using the wrapper :

$contents = file_get_contents('gs://my_bucket/file_backup.txt');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM