[PHP] Papago NMT API 이용을 위한 Class
네이버에서 제공하는 Papago NMT API 이용을 위한 Class 이다. 네이버 파파고 API는 https://developers.naver.com/docs/nmt/reference/ 를 참고한다. API 요청은 아래와 같은 코드로 실행하면 실행에 필요한 Class 코드는 포스트 하단에 있다. API 테스트 전 애플리케이션으 등록해야 하고 아래 코드에서 PAPAGO_NMT_ID, PAPAGO_NMT_SECRET 값을 설정해야 한다.
<?php
require './PapagoNMT.php';
define('PAPAGO_NMT_ID',     'client ID');
define('PAPAGO_NMT_SECRET', 'client Secret');
$papago = new PapagoNMT(PAPAGO_NMT_ID, PAPAGO_NMT_SECRET);
$papago->setSource('en');
$papago->setTarget('ko');
$papago->setText('hello');
$json = $papago->sendRequest();
$result = json_decode($json);
echo 'Translated : '.$result->message->result->translatedText;PapagoNMT.php 파일의 코드이다.
<?php
/**
 * Author : chicpro (https://chicpro.dev)
 */
class PapagoNMT
{
    protected $clientID;
    protected $clientSecret;
    protected $requestURL = 'https://openapi.naver.com/v1/papago/n2mt';
    protected $source;
    protected $target;
    protected $encText;
    public function __construct($clientID, $clientSecret)
    {
        $this->clientID     = $clientID;
        $this->clientSecret = $clientSecret;
    }
    public function setSource($source)
    {
        $this->source = $source;
    }
    public function setTarget($target)
    {
        $this->target = $target;
    }
    public function setText($text)
    {
        $this->encText = trim($text);
    }
    public function sendRequest()
    {
        $headers = array();
        $headers[] = "Content-Type: application/x-www-form-urlencoded; charset=UTF-8";
        $headers[] = "X-Naver-Client-Id: ".$this->clientID;
        $headers[] = "X-Naver-Client-Secret: ".$this->clientSecret;
        $postvars = array(
            'source' => $this->source,
            'target' => $this->target,
            'text'   => $this->encText
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->requestURL);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postvars));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);        
        
        $response = curl_exec ($ch);
        
        $err = curl_error($ch);
        curl_close($ch);
        if($err)
            return $err;
        return $response;
    }
}