Create ads

PHP 5 using JSON with the file_get_contents function

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.

//--- Input data ----------------------------------------------------//
// Address of the Ads service for sending JSON requests (case-sensitive)
$url = '';
// OAuth token for the user that requests will be sent on behalf of
$token = 'TOKEN';
// Login of the advertising agency client
// Required parameter if requests are made on behalf of an advertising agency
$clientLogin = 'CLIENT_LOGIN';
// ID of the ad group to create the new ad in
$adGroupId = GROUP_ID;

//--- Preparing and executing the request -----------------------------------//
// Setting the request HTTP headers
$headers = array(
   "Authorization: Bearer $token",                    // OAuth token. The word Bearer must be used
   "Client-Login: $clientLogin",                      // Login of the advertising agency client
   "Accept-Language: en",                             // Language for response messages
   "Content-Type: application/json; charset=utf-8"    // Data type and request encoding

// Parameters of the request to the Yandex.Direct API server
$params = array(
   'method' => 'add',                                 // Method to use
   'params' => array(
      'Ads' => array(
            'AdGroupId' => $adGroupId,
            'TextAd' => array(                        // Ad parameters
               'Title' => 'Ad title',
               'Text' => 'Ad text',
               'Mobile' => 'NO',
               'Href' => ''
// Converting input parameters to JSON

// Creating the stream context: setting the HTTP headers and message body
$streamOptions = stream_context_create(array(
   'http' => array(
      'method' => 'POST',
      'header' => $headers,
      'content' => $body
   //  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 CA certificate

// Executing the request and getting the result
$result = file_get_contents($url, 0, $streamOptions);

//--- Processing the result ---------------------------//
if ($result === false) { echo "Request execution error!"; }
else {
   // Converting the response from JSON
   $result = json_decode($result);
   if (isset($result->error)) {
      $apiErr = $result->error;
      echo "API error {$apiErr->error_code}: {$apiErr->error_string} - {$apiErr->error_detail} (RequestId: {$apiErr->request_id})";
   else {
      // Extracting the HTTP response headers: RequestId (ID of the request) and Units (information about points)
      foreach ($http_response_header as $header) {
         if (preg_match('/(RequestId|Units):/', $header)) { echo "$header <br>"; }
      // Outputting results
      // Processing all elements in the AddResults array, where each element corresponds to a single ad
      foreach ($result->result->AddResults as $item) {
         // Processing nested elements (these can be Errors, Id, or possibly Warnings)
         foreach ($item as $key => $value) {
            // If the Errors array is present, the ad was not created due to 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>".implode($headers, '<br>')."</pre>";
//echo "Request: <pre>".json_encode($params, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."</pre>";
//echo "Response headers: <pre>".implode($http_response_header, '<br>')."</pre>";
//echo "Response: <pre>".json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."</pre>";