V5.1 Reporting Sample in PHP

Hello!

We'll release a V5.1 reporting sample in PHP to MSDN in a future Microsoft adCenter API doc release.

In the interim, here is the sample. Note the $URI variable is set to V5.1. If you want to use the V5 WSDL, set "V5.1" to "V5". You're encouraged to use the V5.1 version, though, as V5.1 is the latest version.

<?php

// This program requires the following PHP extensions:
// php_soap.dll
// php_openssl.dll

// To ensure that a cached WSDL is not being used,
// disable WSDL caching.
ini_set("soap.wsdl_cache_enabled", "0");

try
{

    $accountId = 489; //Application-specific value.

    // Use either the sandbox or production URI.
// This example is for the sandbox URI.
$URI =
"https://sandboxapi.adcenter.microsoft.com/api/advertiser/v5.1/";
// The following commented-out line contains the production URI.
//$URI = "https://adcenterapi.microsoft.com/api/advertiser/v5.1/";

    // The adCenter API namespace.
$xmlns = "https://adcenter.microsoft.com/api/advertiser/v5";

    // The proxy for the Campaign Management Web service.
$campaignProxy =
$URI . "Reporting/ReportingService.svc?wsdl";

    // The name of the service operation that will be called.
$action = "QueueReport";   

    // The user name, password, and access key are
// expected to be passed in as command-line
// arguments.
// $argv[0] is the PHP file name.
// $argv[1] is the user name.
// $argv[2] is the password.
// $argv[3] is the developer token.
if ($argc !=4)
{
printf("Usage:\n");
printf(
"php file.php username password devtoken\n");
exit(0);
}
$username = $argv[1];
$password = $argv[2];
$developerTokenValue = $argv[3];
$applicationTokenValue="";

    // Assign the credentials to the classes
// that are used by the SOAP headers.
$userCredentials=new UserCredentials();
$userCredentials->Username=$username;
$userCredentials->Password=$password;
$developerToken=new DeveloperToken();
$developerToken->Value=$developerTokenValue;
$applicationToken=new ApplicationToken();
$applicationToken->Value=$applicationTokenValue;

    // Create the SOAP headers.
$headerApplicationToken =
new SoapHeader
(
$xmlns,
'ApplicationToken',
$applicationToken,
false
);
$headerDeveloperToken =
new SoapHeader
(
$xmlns,
'DeveloperToken',
$developerToken,
false
);
$headerUserCredentials =
new SoapHeader
(
$xmlns,
'UserCredentials',
$userCredentials,
false
);

    // Create the SOAP input header array.
$inputHeaders = array
(
$headerApplicationToken,
$headerDeveloperToken,
$headerUserCredentials
);

    // Create the SOAP client.
$opts = array('trace' => true);
$client = new SOAPClient($campaignProxy, $opts);

    $request=new KeywordPerformanceReportRequest();
$request->Format='Xml';
$request->Language='English';
$request->ReportName='My Report';
$request->ReturnOnlyCompleteData=false;
$request->Aggregation='Monthly';
$request->Time=array('PredefinedTime'=>'LastSixMonths');

    $request->Columns=array('AccountName',
'CampaignName',
'Keyword',
'TimePeriod',
'ProductName',
'Impressions',
'Conversions');

    $request->Filter=array('AdDistribution'=>'Search',
'LanguageAndRegion'=>'UnitedStates');
$request->Scope=array('AccountIds'=>array($accountId));

    $soapstruct = new SoapVar($request,
SOAP_ENC_OBJECT,
"KeywordPerformanceReportRequest",
$xmlns);

    $params=array('ReportRequest'=>$soapstruct);
$result = $client->__soapCall($action,array($action.'Request' => $params),null,$inputHeaders,$outputHeaders);

    $reportRequestId=$result->ReportRequestId;
printf("ReportRequestId: %d\n", $reportRequestId);
// Poll to get the status of the report until it is complete.
$waitMinutes = 15;
$maxWaitMinutes = 120;
$elapsedMinutes = 0;
$action = "GetReportStatus";
$params=array('ReportRequestId'=>$reportRequestId);
while (true)
{

        // Wait the specified number of minutes before you poll.
printf("Waiting another %d minutes.\n",
$waitMinutes);
printf("Total wait time so far is %d minutes.\n",
$elapsedMinutes);
sleep($waitMinutes * 60);
$elapsedMinutes += $waitMinutes;

        $result = $client->__soapCall($action,array($action.'Request' => $params),null,$inputHeaders);

        $reportStatus=$result->ReportRequestStatus->Status;
printf("ReportStatus: %s\n", $reportStatus);
if ($reportStatus == 'Success')
{
$downloadURL=$result->ReportRequestStatus->ReportDownloadUrl;

            $handleIn = fopen($downloadURL,"r");
$handleOut = fopen($reportRequestId.".zip", "w");

            while (!feof($handleIn))
{
$content = fread($handleIn, 8192);
fwrite($handleOut,$content);
}
fclose($handleIn);
fclose($handleOut);
break;
}
else
{
if ($reportStatus == 'Pending')
{
// The report is not yet ready.
continue;
}
else
{
// An error occurred.
printf("Error occurred in %s\n", $action);
break;
}
}
}
}

catch (Exception $e)
{
print "$action failed.\n";
// Display the fault code and the fault string.
print $e->faultcode . " " . $e->faultstring . ".\n";

    print "TrackingID: " .
$e->detail->ApiFaultDetail->TrackingId . ".\n";

    // Process operation errors.
if (isset(
$e->detail->ApiFaultDetail->OperationErrors->OperationError
))
{
if (is_array(
$e->detail->ApiFaultDetail->OperationErrors->OperationError
))
{
// An array of operation errors has been returned.
$obj = $e->detail->ApiFaultDetail->OperationErrors->OperationError;
}
else
{
// A single operation error has been returned.
$obj = $e->detail->ApiFaultDetail->OperationErrors;
}
foreach ($obj as $operationError)
{
print "Operation error " .
$operationError->Code . " encountered. ";
print $operationError->Message . "\n";
}
}

    // Output the last request.
print "Last SOAP request:\n";
print $client->__getLastRequest() . "\n";
}

// Definitions for classes that are used by the SOAP headers.
class ApplicationToken
{
public $Value;
}
class DeveloperToken
{
public $Value;
}
class UserCredentials
{
public $Password;
public $Username;
}

// Definition for class used by the Reporting service.
class KeywordPerformanceReportRequest
{
public $Format;
public $Language;
public $ReportName;
public $ReturnOnlyCompleteData;
public $Aggregation;
public $Columns;
public $Filter;
public $Scope;
public $Time;
}

?>

Thank you.

Walter Poupore
Lead Programming Writer
Microsoft adCenter