Search by

starkeen / yandex-search-api

starkeen

Library for using Yandex Search API

Package info

github.com/starkeen/yandex-search-api

pkg:composer/starkeen/yandex-search-api

Statistics

Installs: 912

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v3.0.0 2026-05-31 14:38 UTC

This package is auto-updated.

Last update: 2026-09-09 19:55:21 UTC


README

Library for Yandex Search API

Packagist Version (custom server) Packagist PHP Version Support (specify version) GitHub codecov Quality Gate Status Codacy Badge

Description

This library is a convenient way to interact with the Yandex Search API (the XML interface). It allows for easy integration of Yandex search functionality into your PHP projects. The library encapsulates the complex logic of interacting with the API and provides a simple and understandable interface for executing search queries.

Requirements

  • PHP 8.1 or higher
  • ext-simplexml
  • ext-libxml
  • A PSR-18 HTTP client (psr/http-client: ^1.0)
  • A PSR-17 HTTP factory implementing both RequestFactoryInterface and StreamFactoryInterface (psr/http-factory: ^1.0)
  • A PSR-3 logger (psr/log: ^3.0)

Installation

To install the library, add it to your project using Composer:

composer require starkeen/yandex-search-api

Usage

To use the library, you need to get an API key. You can get it on the Yandex Search API page.

<?php

require_once 'vendor/autoload.php';

use YandexSearchAPI\SearchException;
use YandexSearchAPI\SearchRequest;
use YandexSearchAPI\YandexSearchService;

// Any PSR-17 factory that implements both RequestFactoryInterface and StreamFactoryInterface.
// Popular choices: Nyholm\Psr7\Factory\Psr17Factory, Laminas\Diactoros\RequestFactory, etc.
$factory = new \Nyholm\Psr7\Factory\Psr17Factory();

// Any PSR-18 HTTP client.
// Popular choices: Symfony\Component\HttpClient\Psr18Client, Guzzle 7+ (implements PSR-18), etc.
$httpClient = new \Symfony\Component\HttpClient\Psr18Client();

// Any PSR-3 logger.
$logger = new \Psr\Log\NullLogger();

// Initialize the service with your credentials:
//   - Folder ID from your Yandex Cloud account
//   - API key from your Yandex Cloud account
$service = new YandexSearchService($httpClient, $factory, $logger, 'abcdefg', 'A1B2C3D4');

// Your search query
$searchRequest = new SearchRequest('Кому на Руси жить хорошо?');

try {
    $response = $service->search($searchRequest);

    // Process the results
    foreach ($response->getResults() as $result) {
        echo 'Title: ' . $result->getTitle() . PHP_EOL;
        echo 'URL: ' . $result->getUrl() . PHP_EOL;
        echo 'Domain: ' . $result->getDomain() . PHP_EOL;
        echo 'Snippet: ' . $result->getSnippet() . PHP_EOL;
    }
} catch (SearchException $e) {
    echo $e->getMessage();
}

Configuration

To use the library, you need to provide your Yandex Search API key and your account (folder) ID. You can obtain them by registering your application on the Yandex Cloud Console.

The recommended way is to pass the credentials to the constructor (store them in a configuration file / environment variables rather than hard-coding them):

$service = new YandexSearchService($httpClient, $factory, $logger, 'abcdefg', 'A1B2C3D4');

The setApiId() / setApiKey() setters are still available but deprecated since 2.0 — prefer constructor injection.

If credentials are not provided, search() throws a YandexSearchAPI\ConfigurationException.

Tuning the request

SearchRequest exposes setters to control the query:

use YandexSearchAPI\SearchRequest;
use YandexSearchAPI\constant\Filter;
use YandexSearchAPI\constant\Language;
use YandexSearchAPI\constant\Sort;

$request = new SearchRequest('php');

$request->setNumResults(20);            // results per page (default 10)
$request->setPage(1);                   // page number, starting from 0
$request->setMaxPassages(5);            // passages per document (default 4)
$request->setLanguage(Language::ENGLISH); // RUSSIAN (default) | ENGLISH | TURKISH
$request->setSort(Sort::DATE);          // RELEVANCE (default) | DATE
$request->setFilter(Filter::STRICT);    // NONE (default) | MODERATE | STRICT

Passing a value outside the allowed enum to setLanguage(), setSort() or setFilter() throws a YandexSearchAPI\ConfigurationException.

Working with the response

search() returns a YandexSearchAPI\SearchResponse:

$response = $service->search($request);

$response->getRequestID();   // string — Yandex request id

foreach ($response->getResults() as $result) {
    $result->getTitle();     // string
    $result->getUrl();       // string
    $result->getDomain();    // string — host extracted from the URL
    $result->getSnippet();   // string|null
}

// Pagination (null when the response contains no results)
$pagination = $response->getPagination();
if ($pagination !== null) {
    $pagination->getTotal();       // int|null   — total documents found
    $pagination->getTotalHuman();  // string|null — human-readable count
    $pagination->getCurrentPage(); // int|null
    $pagination->getPageSize();    // int|null
    $pagination->getPagesCount();  // int — total pages (0 if unknown)
}

// Spelling correction (null when Yandex did not suggest one)
$correction = $response->getCorrection();
if ($correction !== null) {
    $correction->getSourceText(); // string — the original query
    $correction->getResultText(); // string — the corrected query
}

Error handling

Exception When it is thrown
YandexSearchAPI\ConfigurationException Missing credentials, or an invalid language / sort / filter value.
YandexSearchAPI\SearchException Transport error, malformed XML, or an error reported by the API (e.g. code 15).

Both exceptions extend \RuntimeException.

Questions and Feedback

If you have questions, issues, or suggestions for improvement, please create a new issue in the Issues section on GitHub.

License

This library is distributed under the MIT license. See the LICENSE file for details.