我在 PHP8.1 中做了一个 GCP 云函数,它连接到 GCP 云存储。我收到一个要处理的文件名,云函数应该打开文件,对其进行解码,然后将结果发送到 pub sub。
我遇到的问题是我无法
fopen
处理云存储中托管的文件。
我需要
fopen
才能工作,因为我用来解码 AVRO 文件的另一个包使用 fopen
来访问文件。
在此先感谢您的帮助。
我已经测试过
file_get_contents
而且效果很好。
我还测试了使用云存储包将文件内容作为流下载,效果也很好。
我还修改了
allow_url_fopen
php 设置,但这并没有改变任何东西。
我正在使用
google/cloud-storage
包,版本 v1.30.2
我正在使用
google/cloud
包,版本 v0.201.0
$bucketName = 'bucket-name';
$filePath = 'file/path/in/bucket';
$this->storageClient->registerStreamWrapper();
$bucket = $this->storageClient->bucket($bucketName);
$object = $bucket->object($filePath);
$newGsFilePath = "gs://$bucketName/$filePath";
error_log(file_exists($newGsFilePath)); // logs "1", signifying that the file exists
error_log(file_get_contents($newGsFilePath)); // logs the contents of the file
$fp = fopen($newGsFilePath, "rb");
error_log(var_export($fp, true)); // logs "NULL". It should be false according to docs when it fails?
error_log(fseek($fp, 0, SEEK_SET)); // logs "-1", presumably because $fp is NULL
fclose($fp);
$stream = $object->downloadAsStream();
$contents = '';
while (!$stream->eof()) {
$contents .= $stream->read(1024);
}
error_log("\$contents: $contents"); // logs the contents of the file
会不会是权限问题?我不是此帐户的管理员,并且是 GCP 的新手
从 Google Cloud Storage 打开的文件不可搜索,这就是为什么
seek($fp, 0)
返回 -1.
可以通过将文件内容复制到本地文件,将文件转换为可搜索文件,使用
file_put_contents('new/local/path/to.file', file_get_contents($newGsFilePath));
我建议您在完成后删除该文件。
感谢@KoalaYoung 帮助我得出这个答案。