Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Get Historical Performance in PHP

The following example shows how to get the historical bid and traffic performance of one or more keywords used in search queries using the Ad Intelligence GetHistoricalKeywordPerformanceByDevice service operation.

This example has been developed and run within the environment described in Getting Started Using PHP with Bing Ads Services.

To download the PHP classes included in the sample, see PHP Production Classes for Bing Ads API.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.

<?php

// You must pass credentials and the URL of the Ad Intelligence WSDL.

// Command line usage:
// php.exe GetPerformanceByDevice username password devToken accountId wsdl 
//

// Disable WSDL caching.

ini_set("soap.wsdl_cache_enabled", "0");
ini_set("soap.wsdl_cache_ttl", "0");

// Define the proxy class for the Ad Intelligence service.

Class ClientProxy
{
    private $username;
    private $password;
    private $developerToken;
    private $wsdlUrl;
    private $accountId;
    private $service;
    private $namespace;

    public function __construct($username, $password, $token, $accountId, $wsdl)
    {
        $this->username = $username;
        $this->password = $password;
        $this->developerToken = $token;
        $this->accountId = $accountId;
        $this->wsdlUrl = $wsdl;
        $this->service = $this->GetProxy($wsdl);
    }

    public function GetAccountId() { return $this->accountId; }
    public function GetService() { return $this->service; }
    public function GetNamespace() { return $this->namespace; }

    // This function gets the namespace from the WSDL, so you do
    // not have to hardcode it in the client.

    private function GetNamespaceForService($url)
    {
        $doc = new DOMDocument;
        $doc->Load($url);

        $xpath = new DOMXPath($doc);
        $query = "/*/@targetNamespace";

        $attrs = $xpath->query($query);

        // The query will return only one node in the node list.

        foreach($attrs as $attr)
        {
            $namespace = $attr->value;
        }

        return $namespace;
    }

    private function GetProxy($wsdl)
    {
        $this->namespace = $this->GetNamespaceForService($wsdl);

        // Define the SOAP headers.

        $headers = array();

        $headers[] = new SoapHeader(
            $this->namespace,
            'CustomerAccountId',
            $this->accountId
            );

        $headers[] = new SoapHeader(
            $this->namespace,
            'DeveloperToken',
            $this->developerToken
            );

        $headers[] = new SoapHeader(
            $this->namespace,
            'UserName',
            $this->username
            );

        $headers[] = new SoapHeader(
            $this->namespace,
            'Password',
            $this->password
            );

        // By default, PHP does not return single item arrays as an array type.
        // To force PHP to always return an array for an array type in the
        // response, specify the SOAP_SINGLE_ELEMENT_ARRAYS feature.

        $options = array(
            'trace' => TRUE,
            'exceptions' => TRUE,
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS
            );

        $proxy = new SOAPClient($this->wsdlUrl, $options);

        $proxy->__setSoapHeaders($headers);

        return $proxy;
    }
}

// Define the possible time intervals.

final class TimeInterval
{
    const Last30Days = 'Last30Days';
    const Last7Days = 'Last7Days';
    const LastDay = 'LastDay';
}

// Define the possible match types.

final class MatchType
{
    const Exact = 'Exact';
    const Phrase = 'Phrase';
    const Broad = 'Broad';
    const Content = 'Content';
    const Aggregate = 'Aggregate';
}

// Define the possible ad positions.

final class AdPosition
{
    const All = 'All';
    const MainLine1 = 'MainLine1';
    const MainLine2 = 'MainLine2';
    const MainLine3 = 'MainLine3';
    const MainLine4 = 'MainLine4';
    const SideBar1 = 'SideBar1';
    const SideBar2 = 'SideBar2';
    const SideBar3 = 'SideBar3';
    const SideBar4 = 'SideBar4';
    const SideBar5 = 'SideBar5';
    const SideBar6 = 'SideBar6';
    const SideBar7 = 'SideBar7';
    const SideBar8 = 'SideBar8';
    const SideBar9 = 'SideBar9';
    const SideBar10 = 'SideBar10';
    const Aggregate = 'Aggregate';
}

// Define the request class.

final class GetHistoricalKeywordPerformanceByDeviceRequest
{
    public $Keywords;
    public $TimeInterval;
    public $TargetAdPosition;
    public $MatchTypes;
    public $Language;
    public $PublisherCountries;
    public $Devices;
}

try
{
    // See Usage for argument values.

    $proxy = new ClientProxy($argv[1], $argv[2], $argv[3], $argv[4], $argv[5]);

    // Specify the request information.

    $request = new GetHistoricalKeywordPerformanceByDeviceRequest();
    $request->Devices = array ( 'Computers', 'Smartphones', 'NonSmartphones' );
    $request->Keywords = array ( 'flower delivery' );
    $request->Language = 'English';
    $request->PublisherCountries = array ( 'US' );
    $request->MatchTypes = array ( MatchType::Broad, MatchType::Phrase, MatchType::Exact );
    $request->TargetAdPosition = AdPosition::MainLine4;
    $request->TimeInterval = TimeInterval::Last7Days;

    $response = $proxy->GetService()->GetHistoricalKeywordPerformanceByDevice($request);

    // Print the historical performance of the specified keywords by device type.

    foreach ($response->KeywordHistoricalPerformances->KeywordHistoricalPerformanceByDevice as $performance)
    {
        print $performance->Keyword;

        if (null == $performance->Device)
        {
            print "\n  There is no historical performance data available for the keyword.\n";
        }
        else
        {
            foreach ($performance->KeywordKPIs->KeywordKPI as $kpi)
            {
                printf(" (%s)\n", $kpi->MatchType);
                printf("    Ad position: %s\n", $kpi->AdPosition);
                printf("    Average bid: %.2f\n", $kpi->AverageBid);
                printf("    Average CPC: %.2f\n", $kpi->AverageCPC);
                printf("    Total cost: %.2f\n", $kpi->TotalCost);
                printf("    Clicks: %s\n", number_format($kpi->Clicks, 0));
                printf("    CTR: %.2f\n", $kpi->CTR);
                printf("    Impressions : %s\n", number_format($kpi->Impressions, 0));
            }
        }

        print "\n";
    }
}
catch (SoapFault $e)
{
    print "GetHistoricalKeywordPerformanceByDevice failed.\n";

    if (isset($e->detail->ApiFaultDetail))
    {
        print "ApiFaultDetail exception encountered\n";
        print "Tracking ID: ".$e->detail->ApiFaultDetail->TrackingId."\n";

        // Process any operation errors.

        if (!empty($e->detail->ApiFaultDetail->OperationErrors))
        {
            $errors = is_array($e->detail->ApiFaultDetail->OperationErrors->OperationError)
                    ? $e->detail->ApiFaultDetail->OperationErrors->OperationError
                    : array('OperationError' => $e->detail->ApiFaultDetail->OperationErrors->OperationError);

            foreach ($errors as $error)
            {
                switch ($error->Code)
                {
                    case 106: // UserIsNotAuthorized
                        print "The user is not authorized to call this operation.\n";
                        break;

                    case 1257: // CampaignServiceMissingLanguage
                        print "The specified language cannot be null or empty.\n";
                        break;

                    case 1505: // CampaignServiceKeywordsArrayShouldNotBeNullOrEmpty
                        print "The list of keywords cannot be null or empty.\n";
                        break;

                    case 3408: // CampaignServiceLanguageAndCountryNotSupported
                        print "One or more of the specified publisher countries is not allowed for the specified language.\n";
                        break;

                    case 3409: // CampaignServiceInvalidMatchTypes
                        print "The list of match types cannot be null or empty.\n";
                        break;

                    case 3412: // CampaignServiceInvalidLanguage
                        print "The specified language is not valid.\n";
                        break;

                    case 3413: // CampaignServiceInvalidPublisherCountry
                        print "One or more of the specified publisher countries is not valid.\n";
                        break;

                    case 3417: // CampaignServiceInvalidDevice
                        print "One or more of the specified devices is not a valid device type.\n";
                        break;

                    default:
                        printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n",
                            $error->ErrorCode, $error->Code, $error->Message, $error->Details);
                        break;
                }
            }
        }

        // Process any batch errors.

        if (!empty($e->detail->ApiFaultDetail->BatchErrors))
        {
            $errors = is_array($e->detail->ApiFaultDetail->BatchErrors->BatchError)
                    ? $e->detail->ApiFaultDetail->BatchErrors->BatchError
                    : array('BatchError' => $e->detail->ApiFaultDetail->BatchErrors->BatchError);

            foreach ($errors as $error)
            {
                print "Batch error encountered for array index ".$error->Index.".\n";
                printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n",
                    $error->ErrorCode, $error->Code, $error->Message, $error->Detail);
            }
        }
    }
    elseif (isset($e->detail->AdApiFaultDetail))
    {
        print "AdApiFaultDetail exception encountered\n";
        print "Tracking ID: ".$e->detail->AdApiFaultDetail->TrackingId ."\n";

        // Process any system errors.

        $errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
                ? $e->detail->AdApiFaultDetail->Errors->AdApiError
                : array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);

        foreach ($errors as $error)
        {
            if (105 == $error->Code) //  InvalidCredentials
            {
                print "The specified credentials are not valid or the account is inactive.\n";
            }
            else
            {
                printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n",
                    $error->ErrorCode, $error->Code, $error->Message, $error->Detail);
            }
        }
    }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";

        // Output the last request/response.

        print "\nLast SOAP request/response:\n";
        print $proxy->GetService()->__getLastRequest()."\n";
        print $proxy->GetService()->__getLastResponse()."\n";
    }
}
catch (Exception $e)
{
    print $e->getCode()." ".$e->getMessage()."\n\n";
    print $e->getTraceAsString()."\n\n";
}

?>
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.