<?php
require 'vendor/autoload.php';
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\AdManager\v201711\Dimension;
use Google\AdsApi\AdManager\AdManagerServices;
use Google\AdsApi\AdManager\AdManagerSession;
use Google\AdsApi\AdManager\AdManagerSessionBuilder;
use Google\AdsApi\AdManager\Util\v201802\ReportDownloader;
use Google\AdsApi\AdManager\Util\v201802\StatementBuilder;
use Google\AdsApi\AdManager\v201711\DateRangeType;
use Google\AdsApi\AdManager\v201802\ExportFormat;
use Google\AdsApi\AdManager\v201802\ReportJob;
use Google\AdsApi\AdManager\v201802\ReportQueryAdUnitView;
use Google\AdsApi\AdManager\v201802\ReportService;
use UnexpectedValueException;
class RunSavedQuery
{
const SAVED_QUERY_ID = 'xxxxxxx';
public static function runExample(
AdManagerServices $AdManagerServices,
AdManagerSession $session,
$savedQueryId, $fileID
) {
$reportService = $AdManagerServices->get($session, ReportService::class);
// Create statement to retrieve the saved query.
$statementBuilder = (new StatementBuilder())->where('id = :id')
->orderBy('id ASC')
->limit(1)
->withBindVariableValue('id', $savedQueryId);
$savedQueryPage = $reportService->getSavedQueriesByStatement(
$statementBuilder->toStatement()
);
$savedQuery = $savedQueryPage->getResults()[0];
if ($savedQuery->getIsCompatibleWithApiVersion() === false) {
throw new UnexpectedValueException(
'The saved query is not compatible with this API version.'
);
}
// Optionally modify the query.
$reportQuery = $savedQuery->getReportQuery();
$reportQuery->setAdUnitView(ReportQueryAdUnitView::HIERARCHICAL);
// Create report job using the saved query.
$reportJob = new ReportJob();
$reportJob->setReportQuery($reportQuery);
$reportJob = $reportService->runReportJob($reportJob);
// Create report downloader to poll report's status and download when ready.
$reportDownloader = new ReportDownloader($reportService, $reportJob->getId());
if ($reportDownloader->waitForReportToFinish()) {
// Write to system temp directory by default.
$filePath = 'googleRevenue.csv.gz';
shell_exec('gunzip $filePath');
printf("Downloading report to %s ...\n", $filePath);
// Download the report.
$reportDownloader->downloadReport(ExportFormat::CSV_DUMP, $filePath);
print "done.\n";
} else {
print "Report failed.\n";
}
}
public static function main()
{
global $argc, $argv;
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()
->build();
$session = (new AdManagerSessionBuilder())->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
$fileID = $argv[1];
self::runExample(new AdManagerServices(), $session, intval(self::SAVED_QUERY_ID),$fileID);
}
}
RunSavedQuery::main();