Create ads

PHP 5 using SOAP with the SoapClient class

This example shows a request using the Ads.add method, along with the result processing and output. To use the example, change the input data to specify the OAuth token and the ID of the group to create the new ad in. For a request on behalf of an agency, also specify the client login.

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

//--- Input data ----------------------------------------------------//
// Address of the WSDL description for the Ads service (case-sensitive)
$wsdlUrl = '';
// OAuth token of the user to execute requests on behalf of
$token = 'TOKEN';
// Login of an advertising agency client
// Required parameter if requests are made on behalf of an advertising agency
$clientLogin = 'CLIENT_TOKEN';
// ID of the ad group to create the new ad in
$adGroupId = GROUP_ID;

//--- Preparing and executing the request -----------------------------------//
// Creating the stream context: set HTTP headers
$streamOptions = stream_context_create(array(
   'http' => array(
      'header' => "Authorization: Bearer $token"."\r\n".    // OAuth token. The word Bearer must be used
                  "Client-Login: $clientLogin"."\r\n".      // Login of the advertising agency client
                  "Accept-Language: en"                     // Language for response messages
   // To fully conform to the HTTPS protocol, you can enable verification of the SSL certificate on the Yandex.Direct API server
   'ssl' => array(
      'verify_peer' => true,
      'cafile' => getcwd().DIRECTORY_SEPARATOR.'CA.pem' // Path to the local copy of the root SSL certificate

// Initializing the SOAP client
$client = new SoapClient($wsdlUrl,
      'trace'             => true,
      'exceptions'        => false,
      'features'          => SOAP_SINGLE_ELEMENT_ARRAYS,
      'cache_wsdl'        => WSDL_CACHE_NONE,
      'encoding'          => 'UTF-8',
      'stream_context'    => $streamOptions

// Parameters for the request to the Yandex.Direct API server
$params = array(
   'Ads' => array(
         'AdGroupId' => $adGroupId,
         // Ad parameters
         'TextAd' => array(
            'Title' => 'Ad title',
            'Text' => 'Ad text',
            'Mobile' => 'NO',
            'Href' => ''

// Executing the request with the "add" method for the Ads service and getting the result
$result = $client->add($params);

//--- Processing results ---------------------------//
if (is_soap_fault($result)) {
   $error = "SOAP Fault: faultcode: {$result->faultcode}, faultstring: {$result->faultstring}";
   if (isset($result->detail->FaultResponse)) { 
      $apiErr = $result->detail->FaultResponse;
      $error .= " detail: {$apiErr->errorCode} - {$apiErr->errorDetail} (RequestId: {$apiErr->requestId})";
   echo $error;
else {
   // Extracting HTTP response headers: RequestId (ID of the request) and Units (information about points)
   $headers = explode("\r\n", $client->__getLastResponseHeaders());
   foreach ($headers as $header) {
      if (preg_match('/(RequestId|Units):/', $header)) { echo "$header<br>"; }

   // Outputting the result
   // Processing all elements in the AddResults array, where each element corresponds to a single ad
   foreach ($result->AddResults as $item) {
      // Processing nested elements (these can be Errors or Id or possibly Warnings)
      foreach ($item as $key => $value) {
         // If the Errors array is present, the ad wasn't created because of an error (there may be multiple errors)
         if ($key == 'Errors') {
            foreach ($value as $errItem) { echo "Error: {$errItem->Code} - {$errItem->Message} ({$errItem->Details})<br>"; }
         else {
            // If the Warnings array is present, the ad was created but there is a warning (there may be multiple warnings)
            if ($key == 'Warnings') {
               foreach ($value as $warItem) { echo "Warning: {$warItem->Code} - {$warItem->Message} ({$warItem->Details})<br>"; }
            echo "Created ad №{$value}<br>";

//--- Debugging information ---------------------------------------------//
//echo "<hr>Request headers:<pre>".$client->__getLastRequestHeaders()."</pre>";
//echo "Request:<pre>".htmlspecialchars($client->__getLastRequest())."</pre>";
//echo "Response headers:<pre>".$client->__getLastResponseHeaders()."</pre>";
//echo "Response:<pre>".htmlspecialchars($client->__getLastResponse())."</pre>";