Is there any way to get data from shared Google Sheet document? - php

I need to create a web page that has to show current prices from Google Sheets. There is a manual https://developers.google.com/api-client-library/php/auth/web-app#protectauthcode but it request authorisation.
Is there any way to import data every time when user open my php page, even if he doesn't have Google account? Or I need to create server-to-server communication and sync every time to json file or my DataBase by cron task?

I managed, here is my solution:
<?php
$apiKey="yourAPIkey";
include_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey($apiKey);
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'SheetID';
$range = 'A1:B';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (count($values) == 0) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
printf("<p>%s, %s</p>", $row[0], $row[1]);
}
}
?>
Install library
Get Simple API access key

Related

How to get google spread sheet data from Sheet ID (From gid) instead of Spread Sheet Id in php

I have one spreadsheet and it contains multiple sheets in tab format .
My code is getting only first spread Sheet data and I have an array which contains all the sheet Id.
My problem is how can I get all the Sheet Data, as I have unique gid for all.
Here SpreadSheet Id is same for all the sheets only sheet id (gid) is different.
I searched a lot, I got only getting data from spreadSheet Id.
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'xxxxxxx--tttttttttttL_ttthhdfhdhshshshshhshsh-84';///random spread sheet id
$range = 'A:G';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();//getting first sheet data only
$sheet_id = array();
// Load Google API library and set up client
// You need to know $spreadsheetID (can be seen in the URL)
$sheetService = $service;
$spreadSheet = $sheetService->spreadsheets->get($spreadsheetId);
$sheets = $spreadSheet->getSheets();
foreach($sheets as $sheet) {
$sheet_id[] = $sheet->properties->sheetId;
}
///$sheet_id -- it will give all the id of sheets, I have 36 sheets in a single spreadsheet, so it's giving 36 ids in an array format
Any Suggestion Will be appreciated ..
After a lots of research , I got the solution and I would like to post my solution.
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/xxxxxx--yyyyyyyyyyyyyy_zzzzzzzzzzzzzzzz/edit
//
$spreadsheetId = 'xxxxxx--yyyyyyyyyyyyyy_zzzzzzzzzzzzzzzz';
$sheet_id = array();
// Load Google API library and set up client
// You need to know $spreadsheetID (can be seen in the URL)
$sheetService = $service;
$spreadSheet = $sheetService->spreadsheets->get($spreadsheetId);
$sheets = $spreadSheet->getSheets();
foreach($sheets as $key=>$sheet) {
// $sheet_id[$key]['gid'] = $sheet->properties->sheetId;
// $sheet_id[$key]['title'] = $sheet->properties->title;
$range = $sheet->properties->title.'!A:G';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values[$sheet->properties->title] = $response->getValues();
}
Here we have only spreadSheet Id , from that We can get titles of all the sheets and from the title we will get all the details :
$range = $sheet->properties->title.'!A:G'; /// loop the title and get the whole sheet value
I can help you with the javascript - you'll have to work out any php for yourself.
If you have the sheet ID, then it is easy to back track to a sheet name, and then to "get" the sheet by name.
1 - getSheets() - gets all the sheets in the current spreadsheet. From this, you can find the sheet name AND the ID of each sheet.
2 - The ID is obtained using getSheetId() - returns the ID of a sheet which you can compare to your list.
3 - The sheet name is obtained using getSheetName() - returns the sheet name which you can use in the method getSheetByName.
4 - getSheetByName(name) - enables you to return a specific sheet with the given name.
The following example gets an object containing the sheetIDs for the ActiveSpreadsheet. It loops through those sheets capturing the respective SheetName and SheetID. Using a nested loop it loops through my list of SheetIDs and compares the SheetID. If the SheetID matches, then the code uses the SheetName to access the sheet by name. If the SheetIDs don't match, it continues though the nexted loop, and then so on.
I've left a number of Logger commands in the code so that the OP can test check details at convenient points in the script.
function so54586032() {
// set up the spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// this is the sheet where I listed my SheetIDs
var mainsheet = ss.getSheetByName("54586032");
// calculate the number of IDs
var Avals = mainsheet.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
//Logger.log("DEBUG: Number of SheetIDs in my list: " + Alast); //DEBUG
// get the list of all sheets in this spreadsheet
var sheets = ss.getSheets();
//calculate the number of sheets
var sheetslength = sheets.length
//Logger.log("DEBUG: Number of actual sheets in this spreadsheet: " + sheetslength); //DEBUG
// LOOP through the actual sheets
for (var i = 0; i < sheets.length; i++) {
//Logger.log("DEBUG: i: " + i + ", sheet name: " + sheets[i].getName() + ", sheet ID: " + sheets[i].getSheetId()); // DEBUG
// loop through the list of sheets
for (var z = 0; z < Alast; z++) {
//Logger.log("DEBUG: z: " + z + ", sheet ID: " + Avals[z][0]); //DEBUG
// test if this shhetID equals the next number in my list
if (sheets[i].getSheetId() == Avals[z][0]) {
//Logger.log("DEBUG: Match: " + sheets[i].getSheetId() + " to " + Avals[z][0]); //DEBUG
// do something
} else {
//Logger.log("DEBUG: No Match"); //DEBUG
};
}
}
}
My list containing relevant SheetIDs
To get sheet's name by GID you can use corresponding Sheets Api:
$spreadsheet_service=new Google_Service_Sheets($client);
$body = new Google_Service_Sheets_GetSpreadsheetByDataFilterRequest([
'data_filters'=>[
"gridRange"=>[
"sheetId"=>SHEET_GID_HERE
]
]
]);
$response = $spreadsheet_service->spreadsheets->getByDataFilter(SPREADSHEET_ID_HERE,$body,['fields'=>'sheets(properties.title)']);
print_r($response->getSheets());

How do i search Google Sheet by a value stored in it

I need to search for a specific value that I stored in a sheet and get the entire row or the location of the cell that the value is store.
Note: My sheet contains more than 10000 rows of data and I need to update a single column. I'm not interested to fetch all the data from the sheet and update it, as it will affect the performance of my site.
please help me to find a solution.
Better late than never!?
Well I also had the same problem but I needed to change multiple fields, I even looked at the links above but nothing in php. The code below also works if you need to change just one field or several. (google translate)
<?php
$myvalue = 'NEW VALUE';
$values = [[$c_id,]];
// make conn with credentials
$client = new \Google_Client();
$client->setApplicationName('Google Sheets with PHP');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/cred.json');
$service = new Google_Service_Sheets($client);
$spreadsheetId = "your-id";
// insert custom range to match with name of spreadsheet and range to search
$range = "COMPLETO!A2:A50000";
$cell_id;
$cell_range;
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values_r = $response->getValues();
if (empty($values_r)) {
print "None Found.\n";
} else {
print "Data found\n";
$range_index = '1';
foreach ($values_r as $row) {
// Show the results in array
$range_index++;
// Match com id do banco de dados
if($row[0] === $c_id){
echo "ID found\n";
echo "$row[0]\n";
echo "Cell ID A${range_index}\n";
$cell_id = "A${range_index}";
// in $cell_range set the effective range to change
// $cell_range = "A${range_index}:CM${range_index}";
break;
}
}
}
$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);
// try Update
$append_sheet = $service->spreadsheets_values->update($spreadsheetId, $cell_range, $body,['valueInputOption' => 'RAW']);
echo "Update Google Sheet\n";
$conn = null;
?>

Google Analytics API (PHP) pull data from second property

For a particular website in my Google Analytics account, two properties are registered for the same website. Don't know who set it up like this first, but for now the first one has data from, say, 2010 to 2012, and the second has 2013 onward. I want to access the second property. Here's what the reporting page looks like (names smudged out):
By following the official tutorial for PHP, I'm able to access the first account and display its total sessions. But I'm not able to access the second account. I thought I'd change the following function:
function getFirstprofileId(&$analytics) {
$index = 0;
$accounts = $analytics->management_accounts->listManagementAccounts();
echo "<pre>";
print_r($accounts);
echo "</pre>";
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[$index]->getId();
$webproperties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[$index]->getId();
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[$index]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
The $index = 0; thing you see is what I did, thinking that just by changing $index to 1 or something, I'll be able to access the next property, but it throws me an error saying Call to a member function getId() on a non-object on the code $firstAccountId = $items[$index]->getId();
Any help will be appreciated.
The problem you are having is probably related to the fact that you are using an old tutorial. Which uses Oauth2 and the old PHP client lib. Because you are only trying to access your own data I recommend you go with a service account.
The current php client lib can be found on github: Google-api-php-client
Below is the code from my tutorial on using a service account with php to access Google Analytics Data.
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P10D'));
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
Make sure that you give the service account email address access at the Account level in Google Analytics.
Code ripped from the tutorial: Google Service account PHP

How pull web statistics using google analytics api through php client

How do I retrieve Google Analytics data through the Google Analytics API using PHP?
Is it possible to get a page wise status through API?
I am working with a website having 30K pages and I need to create a dashboard showing page wise statistics for corresponding user.
Yes it is possible to get the stats you are talking about though the Google Analytics API using PHP.
There is a client library for php that I recommend it can be found on GitHub
Because you will only be accessing your own data I recommend you go with a service account for authentication.
Simple example:
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P10D'));
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
<?php
?>
I you can find a tutorial for that code at Google Service account php

PHP Google Analytics API - Simple example

I am trying to set some basic example of using Google Analytics with this library: https://github.com/google/google-api-php-client
For starter I have:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);
$results = $service->data_ga;
echo '<pre>';
print_r($results);
echo '</pre>';
Q: How to get data from Google Analytics from this query ?
/*
https://www.googleapis.com/analytics/v3/data/
ga?ids=ga%123456
&dimensions=ga%3Acampaign
&metrics=ga%3Atransactions
&start-date=2013-12-25
&end-date=2014-01-08
&max-results=50
*/
$client->setDeveloperKey("MY_SECRET_API");
First of all, for as far as I experienced this won't work for authentication, you'll need to use a OAuth2 authentication. There are two options to do this, using client ID for web application or using a service account. Authorization api
After you have this, you can make a call like this.
(I use a service account here)
First authenticate:
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
Make a call:
$ids = 'ga:123456'; //your id
$startDate = '2013-12-25';
$endDate = '2014-01-08';
$metrics = 'ga:transactions';
$optParams = array(
'dimensions' => 'ga:campaign',
'max-results' => '50'
);
$results = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
//Dump results
echo "<h3>Results Of Call:</h3>";
echo "dump of results";
var_dump($results);
echo "results['totalsForAllResults']";
var_dump($results['totalsForAllResults']);
echo "results['rows']";
foreach ($results['rows'] as $item) {
var_dump($item);
}
You will need to do a http get to get the information from the url.
http://www.php.net/manual/en/function.http-get.php
Remember you will still need to add the Oauth2 auth code to the string before you can send that request. This link might help if you dont have auth code already.
https://developers.google.com/analytics/solutions/articles/hello-analytics-api#authorize_access
what you could do is create a new function...
function ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
{
require_once('classes/google-analytics/gapi.class.php');
$gDimensions = array('campaign');
$gMetrics = array('transactions');
$gSortMetric = NULL;
$gFilter = '';
$gSegment = '';
$gStartDate = '2013-12-25';
$gEndDate = '2014-01-08';
$gStartIndex = 1;
$gMaxResults = $limit;
$ga = new gapi($gaEmail, $gaPass);
$ga->requestReportData($gProfile, $gDimensions, $gMetrics, $gSortMetric, $gFilter, $gSegment, $gStartDate, $gEndDate, $gStartIndex, $gMaxResults);
$gAnalytics_results = $ga->getResults();
//RETURN RESULTS
return $gAnalytics_results;
}
$gProfile = '123456'; // The Profile ID for the account, NOT GA:
$gaEmail = 'YOUR GOOGLE EMAIL'; // Google Email address.
$gaPass = 'YOUR GOOGLE PASSWORD'; // Google Password.
// NOTE: if 2 step login is turned on, create an application password.
$limit = 50;
$ga_campaign_transactions = ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
//OUTPUT
if(!empty($ga_campaign_transactions))
{
$counter=0;
$gaCampResults= array(); // CREATE ARRAY TO STORE ALL RESULTS
foreach($ga_campaign_transactions as $row)
{
$dim_list = $row->getDimesions();
$met_list = $row->getMetrics();
$gaCampResults[$counter]['campaign'] = $dim_list['campaign'];
$gaCampResults[$counter]['transactions'] = $met_list['transactions'];
$counter++;
}
}
if(!empty($gaCampResults))
{
$totalCampTransactions = count($gaCampResults);
?>
<h2>We Found ( <?php echo number_format($totalCampTransactions,0);?> ) Results</h2>
<ul>
<?php
foreach($gaCampResults as $gaRow){
echo "<li>Campaign:".$gaRow['campaign']." | Transactions: ".$gaRow['transactions']."</li>";
}
?>
</ul>
<?php
}
find Analytics Profile ID
Create Google Application password
Hopefully that puts you on the right track :)
untested this, but similar to what I've been using...
Marty

Categories