1
+
2
+ // Copyright 2015 Google Inc. All Rights Reserved.
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+
16
+ require_once __DIR__ . '/vendor/autoload.php ' ;
17
+ // [START all]
18
+ // [START build_service]
19
+ /**
20
+ * Create an authorized client that we will use to invoke BigQuery.
21
+ * @return Google_Service_Bigquery
22
+ * @throws Exception
23
+ */
24
+ function createAuthorizedClient ()
25
+ {
26
+ $ json_credentials_path = getenv ('GOOGLE_APPLICATION_CREDENTIALS ' );
27
+ if (!$ json_credentials_path ) {
28
+ throw new Exception ('Set the environment variable ' .
29
+ 'GOOGLE_APPLICATION_CREDENTIALS to the path to your .json file. ' );
30
+ }
31
+ $ contents = file_get_contents ($ json_credentials_path );
32
+ $ json_array = json_decode ($ contents , true );
33
+ $ credentials = new Google_Auth_AssertionCredentials (
34
+ $ json_array ['client_email ' ],
35
+ [Google_Service_Bigquery::BIGQUERY ],
36
+ $ json_array ['private_key ' ]
37
+ );
38
+ $ client = new Google_Client ();
39
+ $ client ->setAssertionCredentials ($ credentials );
40
+ if ($ client ->getAuth ()->isAccessTokenExpired ()) {
41
+ $ client ->getAuth ()->refreshTokenWithAssertion ();
42
+ }
43
+ $ service = new Google_Service_Bigquery ($ client );
44
+ return $ service ;
45
+ }
46
+ // [END build_service]
47
+ $ bigquery = createAuthorizedClient ();
48
+ $ projectId = '' ;
49
+ if ($ projectId ) {
50
+ // The programmer already set the projectId above.
51
+ } elseif ($ argc > 1 ) {
52
+ $ projectId = $ argv [1 ];
53
+ } else {
54
+ echo "Enter the project ID: " ;
55
+ $ projectId = trim (fgets (STDIN ));
56
+ }
57
+
58
+ // [START run_query]
59
+ // Pack a BigQuery request.
60
+ $ request = new Google_Service_Bigquery_QueryRequest ();
61
+ $ request ->setQuery ('SELECT TOP(corpus, 10) as title, COUNT(*) as unique_words ' .
62
+ 'FROM [publicdata:samples.shakespeare] ' );
63
+ $ response = $ bigquery ->jobs ->query ($ projectId , $ request );
64
+ $ rows = $ response ->getRows ();
65
+ // [END run_query]
66
+
67
+ // [START print_results]
68
+ // Print the results to stdout in a human-readable way.
69
+ echo "\nQuery Results: \n------------ \n" ;
70
+ foreach ($ rows as $ row ) {
71
+ foreach ($ row ['f ' ] as $ field ) {
72
+ printf ('%-30s ' , $ field ['v ' ]);
73
+ }
74
+ echo "\n" ;
75
+ }
76
+ // [END print_results]
77
+ // [END all]
0 commit comments