Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Пример работы с подсказками DaData на PHP
<?php
require('SuggestClient.php');
use Dadata\SuggestClient as SuggestClient;
$token = 'ВАШ API-ключ';
$dadata = new SuggestClient($token);
$query = "москва серпуховская";
if (count($argv) > 1) {
$query = $argv[1];
}
$count = 2;
if (count($argv) > 2) {
$count = $argv[2];
}
$from_bound = NULL;
if (count($argv) > 3) {
$from_bound = $argv[3];
}
$to_bound = NULL;
if (count($argv) > 4) {
$to_bound = $argv[4];
}
$resp = $dadata->address($query, $count, $from_bound, $to_bound);
print "Query: " . $query . "\n";
print "Suggestions: \n";
foreach ($resp->suggestions as $suggestion) {
print $suggestion->unrestricted_value . "\n";
}
?>
<?php
namespace Dadata;
class SuggestClient {
private $url,
$token;
public function __construct($token, $url = 'https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/') {
$this->token = $token;
$this->url = $url;
}
public function suggest($resource, $data) {
$options = array(
'http' => array(
'method' => 'POST',
'header' => array(
'Content-type: application/json',
'Authorization: Token ' . $this->token,
),
'content' => json_encode($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($this->url . $resource, false, $context);
return $result;
}
public function address($query, $count, $from_bound = NULL, $to_bound = NULL) {
$data = array(
'query' => $query,
'count' => $count
);
if (!is_null($from_bound)) {
$data['from_bound'] = array('value' => $from_bound);
}
if (!is_null($to_bound)) {
$data['to_bound'] = array('value' => $to_bound);
}
return json_decode($this->suggest("address", $data));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment