Export (0) Print
Expand All

Create Keywords in PHP

[Version 6 of the Campaign Management service will be deprecated on September 30, 2011. Please migrate your applications to use version 7 or version 8 instead.]

The following PHP example shows how to create keywords by using the Campaign Management Web service. This example assumes that you have already determined which ad group ID will be used for the keywords; you must substitute your ad group ID for the $adGroupID variable that is assigned 501124155 in the following code.

For an example of how to create an ad group and retrieve the ad group ID, see Create Ad Groups in PHP.

<?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
{

    // Application-specific values.
    $accountId = 489;
    $adGroupId = 501124155;
    
    // Use either the sandbox or the production URI.
    // This example is for the sandbox URI.
    $URI =
        "https://sandboxapi.adcenter.microsoft.com/Api/Advertiser/v6/";
    // The following commented-out line contains the production URI.
    //$URI = "https://adcenterapi.microsoft.com/api/advertiser/v6/";

    // The Microsoft adCenter API namespace.
    $xmlns = "https://adcenter.microsoft.com/v6";

    // 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 = "AddKeywords";


    // 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 keywords.
    $keywords = array();

    // Exclude certain words from allowing a match.
    // For example, these ads shouldn't 
    // match a search for "latex gloves", because the 
    // ad group is only for winter hand wear.
    $negativeKeywords = array
    (
        'latex',
        'boxing',
        'softball',
        'baseball'
    );

    // Create an array of keywords.
    $keywords[] = array
    (
        "Text"             => 'mittens',
        "BroadMatchBid"    => array('Amount' => 0.50),
        "ContentMatchBid"  => array('Amount' => 0.50),
        "ExactMatchBid"    => array('Amount' => 0.50),
        "NegativeKeywords" => null
    );

    $keywords[] = array
    (
        "Text"             => 'gloves',
        "BroadMatchBid"    => array('Amount' => 0.50),
        "ContentMatchBid"  => array('Amount' => 0.50),
        "ExactMatchBid"    => array('Amount' => 0.50),
        "NegativeKeywords" => $negativeKeywords
    );

    $params=array
    (
        'AdGroupId'=>$adGroupId,
        'Keywords' => array('Keyword' => $keywords)
    );
    
    // 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 keyword IDs.
    if (isset(
        $result->KeywordIds->long
        ))
    {
        if (is_array($result->KeywordIds->long))
        {
            // An array of keyword IDs has been returned.
            $obj = $result->KeywordIds->long;
        }
        else
        {
            // A single keyword ID has been returned.
            $obj = $result->KeywordIds;
        }
        
        // Display the keyword IDs for the keywords that were created.
        $i = 0;
        foreach ($obj as $keywordId)
        {
            print "'" . $keywords[$i]['Text'] . "' was added with ID " . $keywordId . ".\n";
            $i = $i +1;
        }
    }
}

catch (Exception $e)
{
    print "$action failed.\n";
    
    if (isset($e->detail->EditorialApiFaultDetail))
    {
      print "EditorialApiFaultDetail exception encountered\n";
      print "Tracking ID: " . 
          $e->detail->EditorialApiFaultDetail->TrackingId . "\n";

      // Process any editorial errors.
      if (isset(
          $e->detail->EditorialApiFaultDetail->EditorialErrors->EditorialError
          ))
      {
          if (is_array(
              $e->detail->EditorialApiFaultDetail->EditorialErrors->EditorialError
              ))
          {
              // An array of editorial errors has been returned.
              $obj = $e->detail->EditorialApiFaultDetail->EditorialErrors->EditorialError;
          }
          else
          {
              // A single editorial error has been returned.
              $obj = $e->detail->EditorialApiFaultDetail->EditorialErrors;
          }
          foreach ($obj as $editorialError)
          {
              print "Editorial validation error for item at array index "
                  . $editorialError->Index . "\n";
              print "\tMessage: " . $editorialError->Message . "\n"; 
              print "\tErrorCode: " . $editorialError->ErrorCode . "\n"; 
              print "\tFailed text: " . $editorialError->DisapprovedText . "\n"; 
              print "\tCode: ". $editorialError->Code . "\n"; 
          }
      }

      // Process any batch errors.
      if (isset(
          $e->detail->EditorialApiFaultDetail->BatchErrors->BatchError
          ))
      {
          if (is_array(
              $e->detail->EditorialApiFaultDetail->BatchErrors->BatchError
              ))
          {
              // An array of batch errors has been returned.
              $obj = $e->detail->EditorialApiFaultDetail->BatchErrors->BatchError;
          }
          else
          {
              // A single batch error has been returned.
              $obj = $e->detail->EditorialApiFaultDetail->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";

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

}

?>

Each successfully created keyword is assigned a keyword ID by Microsoft adCenter. The keyword ID is stored in the Id element of the Keyword object.

When you have received the keyword IDs, you should store them for future use. For information about why storing the IDs is recommended, see Creating an Efficient Application. If you don't store them, you can retrieve them by calling the GetKeywordsByAdGroupId service operation. You can retrieve the elements associated with a keyword by calling the GetKeywordsByIds service operation. Calling GetKeywordsByAdGroupId or GetAdKeywordsByIds reduces your API quota. For more information, see Microsoft adCenter Quota API.

When you have successfully created your ads and keywords, the next step is to submit your ad group for approval. For an example about submitting your ad group for approval, see Submit an Ad Group for Approval in PHP.

See Also

Show:
© 2014 Microsoft