PHP에서 ChatGPT API를 연동하여 사용하는 방법을 단계별로 정리해서 안내드리겠습니다.

아래 예시 코드는 ChatGPT API와 간단히 연동하는 방법을 보여줍니다.
예시 파일: chatgpt.php
'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => '당신은 데이터를 분석하고 요약하는 전문가입니다.'],
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.2
];
// cURL을 이용한 API 호출
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// API 응답 받기
$response = curl_exec($ch);
// 에러 처리
if (curl_errno($ch)) {
echo 'API 요청 에러: ' . curl_error($ch);
exit;
}
// 응답 JSON 파싱
$result = json_decode($response, true);
// ChatGPT 응답 출력
if (isset($result['choices'][0]['message']['content'])) {
echo nl2br($result['choices'][0]['message']['content']);
} else {
echo '응답에 오류가 있습니다: ' . $response;
}
curl_close($ch);
💡 주의:
실제로 사용 시, API Key(YOUR_API_KEY)는 꼭 본인의 키로 교체하세요!
PHP에서 엑셀 데이터를 읽어서 분석할 때는 PhpSpreadsheet 패키지를 사용하는 것이 편리합니다.
composer require phpoffice/phpspreadsheet
예시 파일명: excel_to_chatgpt.php
getActiveSheet();
$dataArray = $sheet->toArray();
// 배열 데이터를 텍스트로 변환
$textData = "";
foreach ($dataArray as $row) {
$textData .= implode("\t", $row) . "\n";
}
// 프롬프트 작성
$prompt = "다음 엑셀 데이터를 분석하고 핵심 내용을 요약해주세요.\n\n" . $textData;
// API 요청 데이터 설정
$data = [
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => '당신은 엑셀 데이터를 분석하고 요약하는 전문가입니다.'],
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.2
];
// cURL을 이용한 API 호출
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// API 응답 받기
$response = curl_exec($ch);
// 에러 처리
if (curl_errno($ch)) {
echo 'API 요청 에러: ' . curl_error($ch);
exit;
}
// 응답 JSON 파싱
$result = json_decode($response, true);
// ChatGPT 응답 출력
if (isset($result['choices'][0]['message']['content'])) {
echo nl2br($result['choices'][0]['message']['content']);
} else {
echo '응답에 오류가 있습니다: ' . $response;
}
curl_close($ch);
이 방법으로 PHP에서 ChatGPT API를 연동하여 간단하면서도 강력한 데이터 분석 기능을 구현할 수 있습니다.