Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

카카오 번역 API 사용을 위한 PHP 클라이언트

2018-07-17 by 편리

카카오 번역 API 사용을 위한 PHP 클라이언트 코드이다. PHP 7.0 이상의 환경에서 사용할 수 있다.

카카오 번역 API : https://developers.kakao.com/docs/restapi/translation

<?php
/**
* @author chicpro <chicpro@gmail.com>
* @copyright (c) chicpro
* @link https://chicpro.dev
*/

namespace chicpro\KAKAO;

class TRANSLATE
{
    protected $host;
    protected $appKey;

    protected $query;
    protected $sourceLanguage;
    protected $targetLanguage;

    public function __construct(string $appKey = '')
    {
        $this->host   = 'https://kapi.kakao.com/v1/translation/translate';
        $this->appKey = $appKey;
    }

    public function setHost(string $host)
    {
        $this->host = $host;
    }

    public function setAppKey(string $appKey)
    {
        $this->appKey = $appKey;
    }

    public function setQuery(string $query)
    {
        $this->query = $query;
    }

    public function setSourceLanguage(string $source)
    {
        $this->sourceLanguage = $source;
    }

    public function setTargetLanguage(string $target)
    {
        $this->targetLanguage = $target;
    }

    public function sendRequest()
    {
        $headers = array(
            'Authorization: KakaoAK ' . $this->appKey
        );

        $postData = [
            'src_lang'    => $this->sourceLanguage,
            'target_lang' => $this->targetLanguage,
            'query'       => $this->query
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $this->host);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

        $json = curl_exec($ch);

        if ($errno = curl_errno($ch)) {
            $result = new \stdClass;
            $result->errno = $errno;
            $result->error = 'Curl error: ' . curl_error($ch);
        } else {
            $response = json_decode($json);
            $result = $response;
        }

        return $result;
    }
}

카카오 번역 API 예제 코드는 아래와 같다.

<?php
require __DIR__.'/vendor/autoload.php';

use chicpro\KAKAO\TRANSLATE;

$appKey = '';

$translate = new TRANSLATE();

$translate->setAppKey($appKey);
$translate->setSourceLanguage('kr');
$translate->setTargetLanguage('en');

$query = '지난해 3월 오픈한 카카오톡 주문하기는 현재까지 약 250만명의 회원을 확보했으며, 주문 가능한 프랜차이즈 브랜드는 38개, 가맹점수는 약 1만 5천여곳에 달한다. 전 국민에게 친숙한 카카오톡 UI를 활용하기 때문에 남녀노소 누구나 쉽게 이용할 수 있으며, 별도의 앱을 설치할 필요 없이 카카오톡 내에서 모든 과정이 이뤄지는 것이 특징이다. 지난해 9월 업계 최초로 날짜와 시간을 예약한 뒤 설정한 매장에서 주문 음식을 찾아가는 ‘픽업’ 기능을 도입했고, 올해 1월 스마트스피커 ‘카카오미니’에서 음성을 통해 주문 가능한 메뉴를 안내받을 수 있도록 서비스를 연동하며 차별화를 꾀했다.

중소사업자들이 카카오톡 주문하기에 입점하게 되면 4,300만 카카오톡 이용자들과의 접점을 확보하고, 간편한 주문 과정으로 만족도를 높일 수 있게 된다. 카카오톡 메시지를 통해 신메뉴 출시, 프로모션 등의 소식을 전달할 수 있고, 일대일 채팅 기능을 적용하면 고객과 직접 상담도 가능하다.';

$translate->setQuery($query);

$result = $translate->sendRequest();

print_r($result);

위 코드 중 $appKey는 앱생성 후 REST API 키를 입력해야 한다. 예제 코드의 결과는 아래와 같이 표시된다.

stdClass Object
(
    [translated_text] => Array
        (
            [0] => Array
                (
                    [0] => KakaoTalk, which opened in March last year, has about 2.5 million members so far, 38 franchise brands that can be ordered and about 15,000 franchise stores.
                    [1] => Because it utilizes KakaoTalk UI familiar to the whole people, it is easy for anyone, both young and old, and it is characterized by all the processes in KakaoTalk without having to install a separate app.
                    [2] => In September last year, we introduced the 'picking up' function, which was the first in the industry to book dates and time, and then set up a store to find order food. In January of this year, we launched a service called 'Kakao Mini'
                )

            [1] => Array
                (
                )

            [2] => Array
                (
                    [0] => When small and medium-sized businesses enter KakaoTalk ordering, they will be able to secure contact points with 43 million KakaoTalk users and increase their satisfaction with a simple ordering process.
                    [1] => You can deliver news such as new menu launch and promotion through KakaoTalk message, and you can also consult with customers directly by applying one-on-one chat function.
                )

        )

)

Post navigation

Previous Post:

[PHP] 영카트5에 사용할 수 있는 사이트맵 생성 코드

Next Post:

ssh 접속 세션 유지하기

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • SK 세븐모바일 유심 셀프교체
  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes