구글 사이트자동번역 적용후 검색???
본문
검색은 적용이안되는데 어떠케해결하나요?
데이타베이스에 저장된 데이타는 영어인데 검색은 한국어로........
중간에 언어를 바꿔주는 로직이 필요한거같은데 혹 같은문제로 고민하시는분
계신가요?
답변 2
Google 공식 Translation API를 통해
한국어로 입력된 검색어를 실시간으로 영어로 변환하여 DB 검색하시면 될 것입니다.
1. Composer를 이용한 공식 라이브러리 설치
composer require google/cloud-translate
2. Google Cloud API 준비
- Google Cloud 콘솔에서 Cloud Translation API 활성화
- 서비스 계정 키(JSON 파일)를 다운로드하여 보관 (google-credentials.json)
※ 예시를 만들어 봅니다. ※
프로젝트 루트
├─ vendor/ # composer로 설치한 라이브러리 폴더
├─ google-credentials.json # Google Cloud API 인증 키 파일
├─ translate_search.php # 검색어 번역 처리 파일
└─ search.php # 검색 요청 및 결과 표시 페이지
*google-credentials.json은 Google Cloud에서 발급받은 키.
*Google Cloud Translation API 설치 시 자동으로 vendor/ 폴더에 관련 라이브러리가 추가.
프로젝트 루트에 translate_search.php를 포함하여 번역 기능을 활용
-데이터베이스 연결 설정은 실제 환경에 맞게 수정하세요.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
function translateKoToEn($text) {
$translate = new TranslateClient([
'keyFilePath' => 'google-credentials.json'
]);
$result = $translate->translate($text, [
'source' => 'ko',
'target' => 'en'
]);
return strtolower($result['text']);
}
search.php 생성
<?php
require 'vendor/autoload.php';
include 'translate_search.php';
// 데이터베이스 검색 함수 예시 (실제 환경에 맞게 수정 필요)
function db_search_function($keyword) {
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8mb4', 'db_user', 'db_password');
$stmt = $pdo->prepare("SELECT * FROM products WHERE LOWER(name) LIKE ? LIMIT 10");
$stmt->execute(["%$keyword%"]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// 사용자가 입력한 검색어 처리
$search_korean = isset($_GET['q']) ? trim($_GET['q']) : '';
$search_english = '';
$results = [];
if ($search_korean !== '') {
$search_english = translateKoToEn($search_korean);
$results = db_search_function($search_english);
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>검색 예시</title>
</head>
<body>
<form method="get" action="search.php">
<input type="text" name="q" placeholder="한국어로 검색하세요." value="<?= htmlspecialchars($search_korean) ?>">
<button type="submit">검색</button>
</form>
<?php if ($search_korean !== ''): ?>
<h3>검색어 (한국어): <?= htmlspecialchars($search_korean) ?></h3>
<h3>검색어 (영어 번역): <?= htmlspecialchars($search_english) ?></h3>
<?php if ($results): ?>
<ul>
<?php foreach ($results as $item): ?>
<li><?= htmlspecialchars($item['name']) ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>검색 결과가 없습니다.</p>
<?php endif; ?>
<?php endif; ?>
</body>
</html>
브라우저 주소창에서 아래와 같이 호출
- 검색폼에 검색어(오렌지 주스) 입력/검색 버튼을 누르면 번역후 검색된 결과가 출력.
"http://example.com/search.php?q=오렌지 + 주스"
사용자 입력(오렌지 주스) → translate_search.php로 번역 → DB검색 → 결과, 화면 표시
- 검색 결과 화면
붙임)
- 실 서비스엔, 입력값 검증 및 에러 처리를 반드시 추가.
- 캐싱 처리 권장.
구글커스텀 서치 에이피아이는 무료는 제안이 있습니다. 하루에 100번이라던지 이런식루 초가하면 유료인걸로 알고있는데요
그렇면 정식으로 api 키 승인 받으셔야 합니다. 확인해보시기 바랍니다.