I have been trying to get a single value on google spreadsheet for my school project .Since I am still new in PHP script ,I follow the google guideline which is this link google guidelines .But I cannot find any documentation about getting value on the sheet based on my input .
I plan to use another program to input a single string value and will check whether the value exist on the spreadsheet or not . If yes it will be shown .
I am still quite new in programming with PHP so a code example/simple explanation will be nice . Thanks
You should try the quickstart for PHP. It is correct to read about the document to be familiar with the terms, request and response forms and all the basic stuff about the API. In the quickstart, you will be learning the code implementation of the API starting with the basic function like, listing (getValues()).
Here is a snippet from the quickstart :
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$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) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s\n", $row[0], $row[4]);
}
}
Hope this helps.
Related
Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}
I'm using the Google Sheets API to write some data into the sheets, but so far either I clear it all and write everything again or I write in new rows (which Sheets API does by default).
I am now writing a single column per run, but I need to get the first available column in the sheet, so I can pass it as the range of writing.
This is my code so far:
$sheet = new \Google_Service_Sheets($this->client);
$range = "'" . $sheetName . "'!" . $rangeArg . (strlen($rangeArg) == 2 ? '' : count($data) + 1000);
$response = $sheet->spreadsheets_values->get($this->sheetId, $range);
if (!$clear && $response && $response->values) {
$c = count($response->values);
$newRange = (intval(substr($rangeArg, 1, 1)) + $c);
$newRange = substr($rangeArg, 0, 1) . $newRange . substr($rangeArg, 2);
$range = "'" . $sheetName . "'!" . $newRange . (count($data) + 1000);
}
$options = ['valueInputOption' => 'RAW'];
if ($clear) {
$sheet->spreadsheets_values->clear($this->sheetId, $range, new \Google_Service_Sheets_ClearValuesRequest);
}
$body = new \Google_Service_Sheets_ValueRange(['values' => $data, 'majorDimension' => $columns ? 'COLUMNS' : 'ROWS']);
$ok = $sheet->spreadsheets_values->append($this->sheetId, $range, $body, $options);
}
I saw someone on the internet mentioning getLastColumn() as a function, but it's not available in my version of sheets API apparently or it's just not in this package.
google/apiclient v2.5.0
google/apiclient-services v0.138
google/auth v1.9.0
getLastColumn is an appscript method. Something like that is not available with the php client library is only going to give you google sheets api methods,
The only way to find out whats on the sheet is to buffer it and scan though as you are already doing. Unfortunately with PHP there is really no easy way of doing it.
$response = $service->spreadsheets_values->batchGet($spreadsheetId);
I dont use PHP, but I am 100% sure, that in Google API its closest things on PHP and Python, just syntax of languages would be different
So for get the first free column through Google Sheet API (using Python):
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
DOCUMENT_ID = '1ma8DG3IQJ377900iaFUPu9qXoThuP22buLgEILVfO1M'
def get_service_sacc():
creds_json = 'param-param-1344-fae81984f8a8.json'
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds_service = ServiceAccountCredentials.from_json_keyfile_name(creds_json, scopes).authorize(httplib2.Http())
return build('sheets', 'v4', http=creds_service)
sheet_values = get_service_sacc().spreadsheets().values()
_range = "A1:A9"
# or use _range = "Name of List!A1:A9", if u want to take info not from first list of sheets.
write = sheet_values.append(spreadsheetId=DOCUMENT_ID, range=_range, valueInputOption="USER_ENTERED",body={}).execute()
deal_id = str(write['updates']['updatedRange']).split('!')
little info about how get creds.json, if you wanna make thru this method (its from Service Account (https://cloud.google.com/iam/docs/service-accounts), create it, go to you Cloud Developer Console, create a some project, create service account, append it to project, and also after creation, click on three dots at actions (in account line), click Manage keys -> Add key -> Create new key -> json and end it, than download that json, and put it together in one directory of you project where u start you language logic.)
info about, how append works (https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append)
I am trying to update a google spreadsheet using PHP. Currently the code reliably connects and prints values, but when I try to update values, I get:
Fatal error: Uncaught exception 'Google_Exception' with message '(update) missing required param: 'spreadsheetId''
$service = new Google_Service_Sheets($client);
$spreadsheetId = '[MyID]';
$range = 'Sheet1!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (count($values) == 0) {
print "No data found.\n";
} else {
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s<br>", $row[0], $row[4]);
}
}
$range = 'Sheet1!A2:E2';
$values = [1,2,3,4,5];
$body = new Google_Service_Sheets_ValueRange(['values'=>$values]);
$service->spreadsheets_values->update($spreadsheetId,'Sheet1!A2:E',$body,'raw');
The get() call works perfectly, using the same spreadsheet ID. The update call says that it is missing the spreadsheet ID parameter, but prints the correct spreadsheet ID in the call stack.
Is there an issue with the way I am passing the ID in the update call?
Issue was not actually with spreadsheet ID, but with the way $values and the value input option was passed in. $values should be a two dimensional array, and value input option should be an array not a string. posted the corrected parts of code below for posterity.
$range = 'Sheet1!A2:E2';
$values = [[1,2,3,4,5]];
$inputoption = ['valueInputOption' => "RAW"];
$body = new Google_Service_Sheets_ValueRange(['values'=>$values]);
$service->spreadsheets_values->update($spreadsheetId,$range,$body,$inputoption);
It looks like you are not passing any Oauth2 login credentials, which if I'm not mistaken, is required to add or update information through a Google API (though reading the information does not require this).
https://developers.google.com/sheets/api/quickstart/php
OR, you are not passing the correct information in $value when trying to update (it may be looking for a specific spreadsheet ID, not a range.
I'm using the Google AdWords PHP API to access statistics from our account. However, I'm getting some really strange read outs from the statistics through the api. I'm trying to access the stats for individuals Ads or Adgroups. The statistics returned, however, are way off what they are in the client center. The code I'm using:
$user->SetClientCustomerId($clientId);
$adService = $user->GetService("AdGroupAdService", ADWORDS_VERSION);
$selector = new Selector();
$selector->fields = array("Id", "Name", "Clicks", "Impressions", "Cost");
$selector->predicates[] = new Predicate("AdGroupId", "IN", array($adGroupId));
$selector->dateRange = $dateRange;
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $adService->get($selector);
if (isset($page->entries)) {
foreach ($page->entries as $ad) {
$newLineObject->adName = $ad->name;
$newLineObject->clicks = $ad->ad->AdStats->clicks;
$newLineObject->impressions = $ad->adStats->impressions;
$newLineObject->cost = $ad->ad->AdStats->cost->microAmount/ AdWordsConstants::MICROS_PER_DOLLAR;
}
}
else {
print "No matching ads were found.\n";
}
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
When I print the results I get numbers that are considerably larger than those displayed in the client center. For example, for one partiuclar Ad the API reported 2.000.000 impressions, while the client center showed 56.000.
What am I doing wrong?
Your code seems correct to me. However, you problem may be that your date range in your code is different to the one you see in your client center. Make sure that you keep the same date range when you cross check.
Having tried using the method detailed above extensively, I have altered my code completely. I now use AdHoc Reporting (described here https://developers.google.com/adwords/api/docs/guides/reporting). This method was suggested to me by an AdWords developer. While this does not literally solve my question (i.e. why does the above code return incorrect statistics), it does provide an easy and clean way to obtain the data correctly.
Hi, is there a way to download the BibTeX entry for something from Google Scholar using PHP without having to download the BibTeX manually one by one? For example, setting a search value like "research" and then downloading the related BibTeX from the links automatically through code.
Any help would be appreciated. I tried to get the HTML page, but as I try to get the page contents the "Import to BibTeX" link disappears on the retrieved page contents.
My code:
<?php
$url = 'http://scholar.google.com/scholar?q=honors+college&hl=en&btnG=Search& amp;as_sdt=1%2C4&as_sdtp=on';
$needle = 'Import into bibtex';
$contents = file_get_contents($url);
echo $contents;
if(strpos($contents, $needle)!== false) {
echo 'found';
} else {
echo 'not found';
}
?>
The short answer is No you cannot do this
Google does not provide API's for search / scholar and uses firm rate-limitation. The problem is that for each BibTex entry you need 2 additional requests (1 for the query, 1 for the 'import link' and a final one to get the actual BibTex entry content)
I wrote a script that scrapes google scholar results and finds the BibTex links and saves the results. However, due to the rate limit is not viable and will get blocked almost instantly.
Code can be viewed here: https://gist.github.com/Tessmore/11099509 and is free of use, but at your own risk.
As Tessmore said - you can't. But you can make it work by using Google Scholar Organic Results API from SerpApi that bypasses quota limits and blocks from search engines so you don't have to think about how to reduce the chance of being blocked.
Example:
Install google-search-results-php package first via composer:
$ composer require serpapi/google-search-results-php:2.0
Code to integrate and full example in the online IDE:
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);
require __DIR__ . "/vendor/autoload.php";
function getResultIds () {
$result_ids = array();
$params = [
"engine" => "google_scholar", // parsing engine
"q" => "biology" // search query
];
$search = new GoogleSearch(getenv("API_KEY"));
$response = $search->get_json($params);
foreach ($response->organic_results as $result) {
// print_r($result->result_id);
array_push($result_ids, $result->result_id);
}
return $result_ids;
}
function getBibtexData () {
$bibtex_data = array();
foreach (getResultIds() as $result_id) {
$params = [
"engine" => "google_scholar_cite", // parsing engine
"q" => $result_id
];
$search = new GoogleSearch(getenv("API_KEY"));
$response = $search->get_json($params);
foreach ($response->links as $result) {
if ($result->name === "BibTeX") {
array_push($bibtex_data, $result->link);
}
}
}
return $bibtex_data;
}
print_r(json_encode(getBibtexData(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
?>
Output:
[
"https://scholar.googleusercontent.com/scholar.bib?q=info:KNJ0p4CbwgoJ:scholar.google.com/&output=citation&scisdr=CgXjqB_WGAA:AAGBfm0AAAAAYkm8amenawYn_EBidiCQT5QBh0L1KJEX&scisig=AAGBfm0AAAAAYkm8at9X4P3eIWKUCOc6UriCEDKVsQE0&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:6zRLFbcxtREJ:scholar.google.com/&output=citation&scisdr=CgWhqfi6GAA:AAGBfm0AAAAAYkm8bDoIhTlfTkQFCOzYGax54Bst576o&scisig=AAGBfm0AAAAAYkm8bMe_7Nq4e4pB5lg_eR9jmeGrO8ek&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:6Yb0qOX88FMJ:scholar.google.com/&output=citation&scisdr=CgXn_4MdGAA:AAGBfm0AAAAAYkm8bi8ypCZcFDNEQZYZeoSlvx-U1OSk&scisig=AAGBfm0AAAAAYkm8bnFMnwTWGfkfJDCNEx0C4n-aQwql&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:HFdEElNr3IgJ:scholar.google.com/&output=citation&scisdr=CgXKCFpQGAA:AAGBfm0AAAAAYkm8byukcQCl4WHQx-nSNp2pC1gUFSKG&scisig=AAGBfm0AAAAAYkm8b8EReTVkLwtxfth_pjwMyyY3dqts&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:bs-D_MeC14YJ:scholar.google.com/&output=citation&scisdr=CgXEUXwWGAA:AAGBfm0AAAAAYkm8bwwfMNJrffe16EaGypsem9JlmGTi&scisig=AAGBfm0AAAAAYkm8b6nWlPOQL63fXg6dV2U-JQbpyQyS&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:Rn1qFVLRfKwJ:scholar.google.com/&output=citation&scisdr=CgU-HswkGAA:AAGBfm0AAAAAYkm8cHE1YRK23eHV8nzF89Eem-Bsuz72&scisig=AAGBfm0AAAAAYkm8cDEj8ZrzZjAo2bNX-tjYYYJYQZay&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:d8thHtTwq6YJ:scholar.google.com/&output=citation&scisdr=CgXj7oe9GAA:AAGBfm0AAAAAYkm8cTYamCKGKImjdg5MQdgbxUIIHAEY&scisig=AAGBfm0AAAAAYkm8cTcop1ceKzKYvKAKtvlSQ1EdEtSN&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:IUmhOhGaDaEJ:scholar.google.com/&output=citation&scisdr=CgU0qZ2_GAA:AAGBfm0AAAAAYkm8ctCPwoihZkjbNcdEqSnwa0J3jwDy&scisig=AAGBfm0AAAAAYkm8cingBcYnEp8YRqFDFdN-FAEBgDT7&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:PWsf8O5OMQEJ:scholar.google.com/&output=citation&scisdr=CgVBAJxXGAA:AAGBfm0AAAAAYkm8c3CDKQG0Wh_lWsXU_DZxEJkwZz5y&scisig=AAGBfm0AAAAAYkm8c6I-HjAxD1Gy6FLFDRdxH_qU4OBr&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:yGvgHH8ROuIJ:scholar.google.com/&output=citation&scisdr=CgXFuhOkGAA:AAGBfm0AAAAAYkm8dD0rcSR4LQF8GgTxx865BADtXNDN&scisig=AAGBfm0AAAAAYkm8dIQhodz3rHF9IUdaCSRlhdudACNQ&scisf=4&ct=citation&cd=-1&hl=en"
]
Bibtex data from the first URL:
#article{woese2004new,
title={A new biology for a new century},
author={Woese, Carl R},
journal={Microbiology and molecular biology reviews},
volume={68},
number={2},
pages={173--186},
year={2004},
publisher={Am Soc Microbiol}
}
Disclaimer, I work for SerpApi.