PHP code example of shanginn / yandex-wordstat

1. Go to this page and download the library: Download shanginn/yandex-wordstat library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shanginn / yandex-wordstat example snippets


use Shanginn\YandexWordstat\WordstatClient;
use Shanginn\YandexWordstat\YandexWordstat;

$client = new WordstatClient(getenv('YANDEX_OAUTH_TOKEN'));
$wordstat = new YandexWordstat($client);

$userInfo = $wordstat->userInfo();

echo "Логин: {$userInfo->userInfo->login}\n";
echo "Осталось запросов: {$userInfo->userInfo->dailyLimitRemaining} / {$userInfo->userInfo->dailyLimit}\n";

use Shanginn\YandexWordstat\Enums\DeviceType;

$result = $wordstat->topRequests(
    'яндекс',
    regions: [213, 2], // Москва и Санкт-Петербург
    devices: [DeviceType::PHONE],
);

echo "Всего запросов: {$result->totalCount}\n";
foreach ($result->topRequests as $req) {
    echo "{$req->phrase} — {$req->count} показов\n";
}

// При передаче массива возвращается TopRequestsResult[]
$results = $wordstat->topRequests(['яндекс', 'гугл', 'mail']);

foreach ($results as $result) {
    echo "Фраза: {$result->requestPhrase}, показов: {$result->totalCount}\n";
}

use Shanginn\YandexWordstat\Enums\DynamicsPeriod;

$dynamics = $wordstat->dynamics(
    phrase: 'яндекс',
    period: DynamicsPeriod::MONTHLY,
    fromDate: '2025-01-01',
    toDate: '2025-03-31',
);

foreach ($dynamics->dynamics as $item) {
    echo "Дата: {$item->date} | Показы: {$item->count} | Доля: {$item->share}%\n";
}

use Shanginn\YandexWordstat\Enums\RegionType;

$regionsInfo = $wordstat->regions('яндекс', regionType: RegionType::CITIES);

foreach ($regionsInfo->regions as $region) {
    echo "Регион ID: {$region->regionId} | Показы: {$region->count} | Индекс интереса: {$region->affinityIndex}\n";
}

$tree = $wordstat->getRegionsTree();

foreach ($tree as $country) {
    echo "Страна: {$country['name']} (ID: {$country['id']})\n";
    foreach ($country['children'] as $region) {
        echo "  Регион: {$region['name']} (ID: {$region['id']})\n";
    }
}

use Shanginn\YandexWordstat\Exceptions\WordstatRateLimitException;
use Shanginn\YandexWordstat\Exceptions\WordstatApiErrorException;
use Shanginn\YandexWordstat\Exceptions\WordstatException;

try {
    $result = $wordstat->topRequests('яндекс');
} catch (WordstatRateLimitException $e) {
    // Превышен лимит запросов (HTTP 429)
    echo "Лимит запросов превышен. Повторите позже.\n";
} catch (WordstatApiErrorException $e) {
    // Ошибка API (HTTP 4xx/5xx)
    echo "Ошибка API [{$e->getStatusCode()}]: {$e->getMessage()}\n";
} catch (WordstatException $e) {
    // Общая ошибка SDK
    echo "Ошибка: {$e->getMessage()}\n";
}