假设您的应用程序设置正确,这是我采用的方法的一个示例:
// Authenticate through OAuth 2.0
$credentials = new Google_Auth_AssertionCredentials(
'1111111111-somebigemail@developer.gserviceaccount.com',
[Google_Service_Webmasters::WEBMASTERS_READONLY],
file_get_contents( 'path-to-your-key.p12' )
);
$client = new Google_Client();
$client->setAssertionCredentials( $credentials );
if ( $client->getAuth()->isAccessTokenExpired() ) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Webmasters($client);
// Setup our Search Analytics Query object
$search = new Google_Service_Webmasters_SearchAnalyticsQueryRequest;
$search->setStartDate( date( 'Y-m-d', strtotime( '1 month ago' ) ) );
$search->setEndDate( date( 'Y-m-d', strtotime( 'now' ) ) );
$search->setDimensions( array( 'query' ) );
$search->setRowLimit( 50 );
// Pass our Search Analytics Query object as the second param to our searchanalytics query() method
$results = $service->searchanalytics->query( $url, $search, $options )->getRows();
// Build a CSV
if ( ! empty( $results ) ) {
// Setup our header row
$csv = "Rank,Query,Clicks,Impressions,CTR,Position\r\n";
foreach ( $results as $key => $result ) {
// Columns
$columns = array(
$key + 1,
$result->keys[0],
$result->clicks,
$result->impressions,
round( $result->ctr * 100, 2 ) . '%',
round( $result->position, 1 ),
);
$csv .= '"' . implode( '","', $columns ) . '"' . "\r\n";
}
file_put_contents( dirname( __FILE__ ) . '/data.csv' );
}
我刚刚在我的博客上发布了一篇完整的文章,其中有一个示例类,我开始编写它作为 Webmaster Tools API 和 Analytics API 的包装器。随意将其用作参考:
http://robido.com/php/a-google-webmaster-tools-api-php-example-using-search-analytics-api-to-download-search-analytics-data-as-csv-with-the-新oauth-2-0-方法/