首页 > 解决方案 > 在我的 php 代码中验证和使用 Google 的 BigQuery

问题描述

我正在使用我的 BigQuery 数据设置我的客户端应用程序,我需要使用 php 构建它(我不是专家)。

我想在我的服务器中使用 php 进行身份验证并能够构建查询。

我无法进行身份验证,因为我看到了不同的解决方案,这些解决方案似乎已经过时或不完整。

我有 JSON 密钥和我想要但不知道正确等待向 BigQuery 进行身份验证的项目。

有人可以告诉我如何正确地做到这一点吗?如果我需要另一个库(比如 google cloud auth?)

标签: phpgoogle-cloud-platformgoogle-bigquerygoogle-authentication

解决方案


这是代码片段:

public function getServiceBuilder() {
            putenv('GOOGLE_APPLICATION_CREDENTIALS=path_to_service_account.json');

        $builder = new ServiceBuilder(array(
            'projectId' => PROJECT_ID
        ));

        return $builder;
}

那么你可以像这样使用

$builder = $this->getServiceBuilder();
    $bigQuery = $builder->bigQuery();
    $job = $bigQuery->runQueryAsJob('SELECT .......');

    $backoff = new ExponentialBackoff(8);
    $backoff->execute(function () use ($job) {
        $job->reload();
        $this->e('reloading job');
        if (!$job->isComplete()) {
            throw new \Exception();
        }
    });
    if (!$job->isComplete()) {
        $this->e('Job failed to complete within the allotted time.');
        return false;
    }

    $queryResults = $job->queryResults();

    if ($queryResults->isComplete()) {
        $i = 0;
        $rows = $queryResults->rows();

        foreach ($rows as $row) {

(已编辑)

您可能需要添加:

use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;
use Google\Cloud\ExponentialBackoff;

和 composer.json (这只是一个例子,它可能与实际版本不同)

{
    "require": {
        "google/cloud": "^0.99.0"
    }
}

推荐阅读