Get statistics for a selection of rows

PHP 5 using JSON with the cURL library

This example shows a request to the Reports service, along with the result processing and output. The mode for generating the report is selected automatically. If the report is added to the queue in offline mode, repeated requests are made.

The report contains statistics on impressions, clicks, and expenditures for all the advertiser's campaigns for the past month, with grouping by date, campaign name, and ad ID. The report filters out rows with the most expensive clicks, where the number of clicks is less than the set value and the CPC is higher than the set value.

To use the example, specify the OAuth access token in the input data. For a request on behalf of an agency, also specify the client login. In the request message body, specify the thresholds for the number of clicks and the CPC, as well as a report name that is unique among the advertiser's reports.


// Settings for outputting the buffer contents, which allow you to print to the screen
// when using the sleep function

//--- Input data ---------------------------------------------------//
// Address of the Reports service for sending JSON requests (case-sensitive)
$url = '';
// OAuth token of the user that requests will be executed on behalf of
$token = 'TOKEN';
// Login of the advertising agency client
// Required if requests are sent for an advertising agency
$clientLogin = 'CLIENT_LOGIN';

//--- Preparing the request -----------------------------------------------//
// Creating the request body
$params = [
    "params" => [
        "SelectionCriteria" => [
            "Filter" => [
                    "Field" => "Clicks",
                    "Operator" => "LESS_THAN",
                    "Values" => ["CLICK_THRESHOLD"]
                    "Field" => "Cost",
                    "Operator" => "GREATER_THAN",
                    "Values" => ["COST_THRESHOLD"]
        "FieldNames" => ["Date", "CampaignName", "AdId", "Impressions", "Clicks", "Cost"],
        "ReportName" => "REPORT_NAME",
        "ReportType" => "AD_PERFORMANCE_REPORT",
        "DateRangeType" => "LAST_MONTH",
        "Format" => "TSV",
        "IncludeVAT" => "NO",
        "IncludeDiscount" => "NO"

// Transforming request input parameters to JSON
$body = json_encode($params);

// Creating request HTTP headers
$headers = array(
    // OAuth token. The word Bearer must be used
    "Authorization: Bearer $token",
    // Login of the advertising agency client
    "Client-Login: $clientLogin",
    // Response language
    "Accept-Language: en", 
    // Report generation mode
    "processingMode: auto",
    // Format for currency values in the report
    // "returnMoneyInMicros: false",
    // Don't include the row with the report name and date range in the report
    // "skipReportHeader: true",
    // Don't include the row with column names in the report
    // "skipColumnHeader: true",
    // Don't include the row with the number of statistics rows in the report
    // "skipReportSummary: true" 


// cURL initialization
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);

To make full use of the HTTPS protocol, you can verify the SSL certificate for the Yandex.Direct API server.
To enable verification, set the CURLOPT_SSL_VERIFYPEER option to true. Also comment out the line with the CURLOPT_CAINFO option and specify the path to the local copy of the root SSL certificate.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($curl, CURLOPT_CAINFO, getcwd().'\CA.pem');

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// --- Starting the request execution loop ---
// If the HTTP 200 response is received, report contents are output
// If the HTTP 201 or 202 response is received, the request is repeated
while (true) {

    $result = curl_exec($curl);

    if (!$result) {

        echo ('cURL error: '.curl_errno($curl).' - '.curl_error($curl));


    } else {

        // Separating HTTP headers and the response body
        $responseHeadersSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $responseHeaders = substr($result, 0, $responseHeadersSize);
        $responseBody = substr($result, $responseHeadersSize);

        // Getting the HTTP status code
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        // Extracting HTTP response headers
        // Request ID
        $requestId = preg_match('/RequestId: (\d+)/', $responseHeaders, $arr) ? $arr[1] : false;
        //  Recommended number of seconds to wait before rechecking report readiness
        $retryIn = preg_match('/retryIn: (\d+)/', $responseHeaders, $arr) ? $arr[1] : 60;

        if ($httpCode == 400) {

            echo "Invalid request parameters, or the report queue has reached its limit<br>";
            echo "RequestId: {$requestId}<br>";
            echo "JSON code of the request:<br>{$body}<br>";
            echo "JSON code of the server response:<br>{$responseBody}<br>";


        } elseif ($httpCode == 200) {

            echo "Report created<br>";
            echo "RequestId: {$requestId}<br>";
            echo $responseBody;


        } elseif ($httpCode == 201) {

            echo "Report added to the queue in offline mode<br>";
            echo "Resending request in {$retryIn} seconds<br>";
            echo "RequestId: {$requestId}<br>";


        } elseif ($httpCode == 202) {

            echo "The report is generated in offline mode.<br>";
            echo "Resending the request in {$retryIn} seconds<br>";
            echo "RequestId: {$requestId}<br>";


        } elseif ($httpCode == 500) {

            echo "Error generating the report. Please resend the request later<br>";
            echo "RequestId: {$requestId}<br>";
            echo "JSON code for the server response:<br>{$responseBody}<br>";


        } elseif ($httpCode == 502) {

            echo "Server timeout for generating the report.<br>";
            echo "Try changing the request parameters: set a shorter time period and request less data.<br>";
            echo "RequestId: {$requestId}<br>";


        } else {

            echo "Unexpected error.<br>";
            echo "RequestId: {$requestId}<br>";
            echo "JSON code for the request:<br>{$body}<br>";
            echo "JSON code for the server response:<br>{$responseBody}<br>";