Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Пример работы с API стандартизации DaData на PHP (через cUrl)
<?php
class Dadata {
public function __construct($apiKey, $secretKey) {
$this->apiKey = $apiKey;
$this->secretKey = $secretKey;
}
public function clean($type, $data) {
$requestData = array($data);
return $this->executeRequest("https://dadata.ru/api/v2/clean/$type", $requestData);
}
public function cleanRecord($structure, $record) {
$requestData = array(
"structure" => $structure,
"data" => array($record)
);
return $this->executeRequest("https://dadata.ru/api/v2/clean", $requestData);
}
private function prepareRequest($curl, $data) {
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Token ' . $this->apiKey,
'X-Secret: ' . $this->secretKey,
));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
}
private function executeRequest($url, $data) {
$result = false;
if ($curl = curl_init($url)) {
$this->prepareRequest($curl, $data);
$result = curl_exec($curl);
$result = json_decode($result, true);
curl_close($curl);
}
return $result;
}
}
$apiKey = "ВАШ_API_КЛЮЧ";
$secretKey = "ВАШ_СЕКРЕТНЫЙ_КЛЮЧ";
$dadata = new Dadata($apiKey, $secretKey);
// Стандартизация одного значения конкретного типа
$result = $dadata->clean('name', 'Сергей Владимерович Иванов');
print_r($result);
// Стандартизация нескольких значений одного типа
// Допускается не более 1 ФИО, 3 адресов, 3 телефонов, 3 email
$structure = array("PHONE", "PHONE", "PHONE");
$record = array("8 916 823 3454", "495 663-12-53", "457 07 25");
$result = $dadata->cleanRecord($structure, $record);
print_r($result);
@katarsies

This comment has been minimized.

Copy link

katarsies commented Oct 19, 2017

День добрый!
Нужно ещё в классе объявить переменные $this->apiKey и $this->secretKey чтоб всё заработало.

@lazitskiy

This comment has been minimized.

Copy link

lazitskiy commented Nov 17, 2017

Они инжектятся в конструктор

$apiKey = "ВАШ_API_КЛЮЧ";
$secretKey = "ВАШ_СЕКРЕТНЫЙ_КЛЮЧ";
$dadata = new Dadata($apiKey, $secretKey);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.