Stas
8/6/2018 - 7:51 AM

Пример работы с DaData API на PHP

Пример работы с DaData API на PHP

<?php

namespace Dadata;

class DadataClient {
    private $url,
            $token;

    public function __construct($url, $token, $secret) {
        $this->url = $url;
        $this->token = $token;
        $this->secret = $secret;
    }

    public function clean($data) {
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => array(
                    'Content-type: application/json',
                    'Authorization: Token ' . $this->token,
                    'X-Secret: ' . $this->secret
                    ),
                'content' => json_encode($data),
            ),
        );

        $context = stream_context_create($options);
        $result = file_get_contents($this->url, false, $context);
        return $result;
    }

}

?>
<?php 

require('DadataClient.php');
use Dadata\DadataClient as DadataClient;

$url = 'https://dadata.ru/api/v2/clean';
$token = 'ВАШ API-КЛЮЧ';
$secret = 'ВАШ СЕКРЕТНЫЙ КЛЮЧ';
$dadata = new DadataClient($url, $token, $secret);

$data = array(
    "structure" => array("ADDRESS"),
    "data" => array(array("Москва, Милютинский 13"))
);

echo "\nRequest:\n";
var_dump($data);

echo "Response:\n";
$resp = json_decode($dadata->clean($data));
var_dump($resp);

?>