必须先获取API密钥、构造JSON请求体并正确设置Authorization和Content-Type头,否则返回401或400错误;需登录DeepSeek官网创建密钥,用cURL发送含model、messages等字段的POST请求,再解析响应输出content。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

要用PHP调用DeepSeek API完成文本生成任务,必须先获取有效API密钥、构造符合要求的JSON请求体,并正确设置Authorization和Content-Type头,否则会返回401或400错误。
准备API密钥和基础配置
登录DeepSeek官网控制台,在「API Keys」页面点击「Create new key」生成密钥,复制后保存到安全位置——【密钥一旦关闭页面就无法再次查看,务必立即复制】。
新建一个PHP文件(如deepseek.php),在开头定义变量:
$api_key = 'sk-xxxxxx'; // 替换为你自己的密钥
$url = 'https://api.deepseek.com/v1/chat/completions';
立即学习“PHP免费学习笔记(深入)”;
构造并发送POST请求
方法一:使用cURL(推荐)
初始化cURL句柄→设置URL→启用返回响应体→设置POST方法→组装JSON数据→添加请求头→执行请求→获取响应→关闭句柄。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = json_encode([
'model' => 'deepseek-chat',
'messages' => [['role' => 'user', 'content' => '你好,请用中文简单介绍你自己']],
'temperature' => 0.7
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $api_key,
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
解析并输出结果
检查$curl是否执行成功,再用json_decode解析响应:
if ($response === false) {
die('cURL error: ' . curl_error($ch));
}
$result = json_decode($response, true);
if (isset($result['choices'][0]['message']['content'])) {
echo $result['choices'][0]['message']['content'];
} else {
echo "API返回异常:" . ($result['error']['message'] ?? '未知错误');
}



















