Export (0) Print
Expand All

Add Ad Groups in PHP

The following example shows how to create ad groups within a campaign using the Campaign Management AddAdGroups 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

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

try
{

    // Application-specific values.
    $accountId = <youraccountid>;
    $campaignId = <yourcampaignid>;
    
    // Use either the sandbox or the production URI.
    // This example is for the sandbox URI.
    $URI =
        "https://api.sandbox.bingads.microsoft.com/api/advertiser/v8/";
    // The following commented-out line contains the production URI.
    //$URI = "https://adcenterapi.microsoft.com/api/advertiser/v8/";

    // The Bing Ads API namespace.
    $xmlns = "https://adcenter.microsoft.com/v8";

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

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


    // The user name, password, and developer token 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];
    $developerToken = $argv[3];
    $applicationToken = "";

    // Create the SOAP headers.
    $headerApplicationToken = 
        new SoapHeader
        (
            $xmlns,
            'ApplicationToken',
            $applicationToken,
            false
        );
    $headerDeveloperToken = 
        new SoapHeader
        (
            $xmlns,
            'DeveloperToken',
            $developerToken,
            false
        );
    $headerUserName = 
        new SoapHeader
        (
            $xmlns,
            'UserName',
            $username,
            false
        );
    $headerPassword = 
        new SoapHeader
        (
            $xmlns,
            'Password',
            $password,
            false
        );

    $headerCustomerAccountId = 
        new SoapHeader
        (
            $xmlns,
            'CustomerAccountId',
            $accountId,
            false
        );


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

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

    // Create an array of ad groups.
    $adGroups = array();
    
    // These ad groups will be for search advertising.
    // Update as needed if other distributions are required.
    $adDistribution = 'Search';
    
    // This example will use today's date as the start date for
    // the ad groups.
    // See how null is used for the StartDate assignments in the
    // $adGroups array.

    // Use 31 December 2012 as the end date for the ad groups.
    $endDay = 31;
    $endMonth = 12;
    $endYear = 2012;

    // Create an array of ad groups.
    $adGroups[] = array
    (
        "Name"              => 'Hand wear',
        "AdDistribution"    => $adDistribution,
        "BiddingModel"      => 'Keyword',
        "PricingModel"      => 'Cpc',
        "ExactMatchBid"     => array('Amount' => 10.25),
        "StartDate"         => null,
        "EndDate"           => array
                               (
                                   'Day'   => $endDay,
                                   'Month' => $endMonth,
                                   'Year'  => $endYear
                               ),
        "Language" => 'English',
    );

    $adGroups[] = array
    (
        "Name"              => 'Head wear',
        "AdDistribution"    => $adDistribution,
        "BiddingModel"      => 'Keyword',
        "PricingModel"      => 'Cpc',
        "ExactMatchBid"     => array('Amount' => 5.00),
        "PhraseMatchBid"    => array('Amount' => .75),
        "StartDate"         => null,
        "EndDate"           => array
                               (
                                   'Day'   => $endDay,
                                   'Month' => $endMonth,
                                   'Year'  => $endYear
                               ),
        "Language" => 'English',
    );

    // Specify the parameters for the SOAP call.
    $params = array
    (
        'CampaignId' => $campaignId,
        'AdGroups' => array('AdGroup' => $adGroups)
    );
   
    // Execute the SOAP call.
    $result = $client->__soapCall
    (
        $action,
        array( $action.'Request' => $params ),
        null,
        $inputHeaders,
        $outputHeaders
    );
    
     print "Successful $action call.\n";
     print "TrackingId output from response header: "
          . $outputHeaders['TrackingId']
          . ".\n";
     
     // Insert a blank line to separate the text that follows.
     print "\n";
     
    // Retrieve the ad group IDs.
    if (isset(
        $result->AdGroupIds->long
        ))
    {
        if (is_array($result->AdGroupIds->long))
        {
            // An array of ad group IDs has been returned.
            $obj = $result->AdGroupIds->long;
        }
        else
        {
            // A single ad group ID has been returned.
            $obj = $result->AdGroupIds;
        }
        
        // Display the ad group IDs for the ad groups that were created.
        $i = 0;
        foreach ($obj as $adGroupId)
        {
            print "Ad group named " . $adGroups[$i]['Name'] . " was created" . 
            " with adGroup ID " . $adGroupId . ".\n";
            $i = $i + 1;
        }
    }
}

catch (Exception $e)
{
    print "$action 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 (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 encountered:\n";
              print "\tMessage: ". $operationError->Message . "\n"; 
              print "\tDetails: ". $operationError->Details . "\n"; 
              print "\tErrorCode: ". $operationError->ErrorCode . "\n"; 
              print "\tCode: ". $operationError->Code . "\n"; 
          }
      }

      // Process any batch errors.
      if (isset(
          $e->detail->ApiFaultDetail->BatchErrors->BatchError
          ))
      {
          if (is_array(
              $e->detail->ApiFaultDetail->BatchErrors->BatchError
              ))
          {
              // An array of batch errors has been returned.
              $obj = $e->detail->ApiFaultDetail->BatchErrors->BatchError;
          }
          else
          {
              // A single batch error has been returned.
              $obj = $e->detail->ApiFaultDetail->BatchErrors;
          }
          foreach ($obj as $batchError)
          {
              print "Batch error encountered for array index " . $batchError->Index . ".\n";
              print "\tMessage: ". $batchError->Message . "\n"; 
              print "\tDetails: ". $batchError->Details . "\n"; 
              print "\tErrorCode: ". $batchError->ErrorCode . "\n"; 
              print "\tCode: ". $batchError->Code . "\n"; 
          }
      }
    }

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

      // Process any operation errors.
      if (isset(
          $e->detail->AdApiFaultDetail->Errors
          ))
      {
          if (is_array(
              $e->detail->AdApiFaultDetail->Errors
              ))
          {
              // An array of errors has been returned.
              $obj = $e->detail->AdApiFaultDetail->Errors;
          }
          else
          {
              // A single error has been returned.
              $obj = $e->detail->AdApiFaultDetail->Errors;
          }
          foreach ($obj as $Error)
          {
              print "Error encountered:\n";
              print "\tMessage: ". $Error->Message . "\n"; 
              print "\tDetail: ". $Error->Detail . "\n"; 
              print "\tErrorCode: ". $Error->ErrorCode . "\n"; 
              print "\tCode: ". $Error->Code . "\n"; 
          }
      }

    }

    // Display the fault code and the fault string.
    print $e->faultcode . " " . $e->faultstring . ".\n";

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

?>

Community Additions

Show:
© 2015 Microsoft