使用PHP 编码最新API v201506 和v201509 以获得日期范围内的成本总和。
function getAdwordSumOfCost(AdWordsUser $user, $filePath, $startDate=null, $endDate=null, $campaignId = null) {
$basePath = __DIR__."/../../";//path to google ads api
// Load the service, so that the required classes are available.
$user->LoadService('ReportDefinitionService', 'v201509');
include_once($basePath.'vendor/googleads/googleads-php-lib/src/Google/Api/Ads/AdWords/v201509/CampaignService.php');
$selector = new Selector();
$selector->fields = array('CampaignId', 'AdGroupId', 'Id', 'Criteria',
'CriteriaType', 'Impressions', 'Clicks', 'Cost');
if($campaignId)
$selector->predicates[] = new Predicate('CampaignId', 'IN', array($campaignId));
if($startDate && $endDate) {
$selector->dateRange = new DateRange($startDate, $endDate);
}
// Create report definition.
include_once($basePath.'vendor/googleads/googleads-php-lib/src/Google/Api/Ads/AdWords/Util/v201509/ReportClasses.php');
$reportDefinition = new ReportDefinition();
$reportDefinition->selector = $selector;
$reportDefinition->reportName = 'Criteria performance report #' . uniqid();
$reportDefinition->dateRangeType = 'CUSTOM_DATE';
$reportDefinition->reportType = 'CRITERIA_PERFORMANCE_REPORT';
$reportDefinition->downloadFormat = 'XML';
// Exclude criteria that haven't recieved any impressions over the date range.
$reportDefinition->includeZeroImpressions = false;
// Set additional options.
$options = array('version' => 'v201509');
// Download report.
include_once($basePath.'vendor/googleads/googleads-php-lib/src/Google/Api/Ads/AdWords/Util/v201509/ReportUtils.php');
ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);
$doc = new DOMDocument();
$doc->loadXML(file_get_contents($filePath));
$xp = new DOMXPath($doc);
$q = $xp->query("/report/table/row/@cost");
$cost = 0.00;
foreach($q as $el) {
$v = $el->textContent;
$cost += $v / 1000000;
}
return $cost;
}
用法:
$adwordsUser = new AdWordsUser();
//pass Adwords clientID, you can also pas campaign id as well if you want to get calculation only for a single campaign
$adwords = new Adwords('111-111-111');
//Will give you cost for yesterday
$cost = $adwords->getAdwordSumOfCost($adwordsUser, '/path/to/storage/result.xml', date('Ymd', strtotime('-1 day')), date('Ymd', strtotime('-1 day')));