从0到1搭建PHP热点新闻聚合与Ai对接平台,小白也能轻松上手!
每天热点新闻聚合站php采集。怎么获得他们的接口呢?自己找到他们对应的接口就行了。小编找了几个。先看看封装的几个效果比如百度的:https://www.wenyunfang.com/ecmsapi/duomeiti/hot/baidu/
比如抖音的:https://www.wenyunfang.com/ecmsapi/duomeiti/hot/douyin/
比如知乎的:https://www.wenyunfang.com/ecmsapi/duomeiti/hot/zhihu/
细心的都看见了,就是最后的请求参数变了而已就能获取到他们对应的热点新闻了。不啰嗦开始上代码。有点长直接复制过去调试就行
<?php// Curl请求函数function Curl($url, $header = ["accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9","Accept-Encoding: gzip, deflate, br","Accept-Language: zh-CN,zh;q=0.9","Connection: keep-alive","User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1"], $cookie = null, $refer = 'https://www.baidu.com'){$ip = rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255);$header[] = "CLIENT-IP:" . $ip;$header[] = "X-FORWARDED-FOR:" . $ip;$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_REFERER,$refer);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $output = curl_exec($ch);curl_close($ch);return $output;}// 少数派 热榜function sspai(){$jsonRes = json_decode(Curl('https://sspai.com/api/v1/article/tag/page/get?limit=100000&tag=%E7%83%AD%E9%97%A8%E6%96%87%E7%AB%A0', null, null, "https://sspai.com"), true);$tempArr = [];foreach ($jsonRes['data'] as $k => $v) {array_push($tempArr, ['index' => $k + 1,'title' => $v['title'],'createdAt' => date('Y-m-d', $v['released_time']),'other' => $v['author']['nickname'],'like_count' => $v['like_count'],'comment_count' => $v['comment_count'],'url' => 'https://sspai.com/post/' . $v['id'],'mobilUrl' => 'https://sspai.com/post/' . $v['id']]);}return ['success' => true,'title' => '少数派','subtitle' => '热榜','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}// 抖音 热搜榜function douyin(){$jsonRes = json_decode(Curl('https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/', null, null, "https://www.douyin.com"), true);$tempArr = [];foreach ($jsonRes['word_list'] as $k => $v) {array_push($tempArr, ['index' => $k + 1,'title' => $v['word'],'hot' => round($v['hot_value'] / 10000, 1) . '万','url' => 'https://www.douyin.com/search/' . urlencode($v['word']),'mobilUrl' => 'https://www.douyin.com/search/' . urlencode($v['word'])]);}return ['success' => true,'title' => '抖音','subtitle' => '热搜榜','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}// 哔哩哔哩 全站日榜function bilibili_rankall(){$jsonRes = json_decode(Curl('https://api.bilibili.com/x/web-interface/ranking/v2?rid=0&type=all', null, null, "https://www.bilibili.com"), true);$tempArr = [];foreach ($jsonRes['data']['list'] as $k => $v) {array_push($tempArr, ['index' => $k + 1,'title' => $v['title'],'pic' => $v['pic'],'desc' => $v['desc'],'hot' => round($v['stat']['view'] / 10000, 1) . '万','url' => $v['short_link'],'mobilUrl' => $v['short_link']]);}return ['success' => true,'title' => '哔哩哔哩','subtitle' => '全站日榜','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}// 哔哩哔哩 热搜榜function bilibili_hot(){$jsonRes = json_decode(Curl('https://app.bilibili.com/x/v2/search/trending/ranking', null, null, "https://www.bilibili.com"), true);$tempArr = [];foreach ($jsonRes['data']['list'] as $k => $v) {array_push($tempArr, ['index' => $v['position'],'title' => $v['keyword'],'url' => 'https://search.bilibili.com/all?keyword=' . $v['keyword'] . '&order=click','mobilUrl' => 'https://search.bilibili.com/all?keyword=' . $v['keyword'] . '&order=click']);}return ['success' => true,'title' => '哔哩哔哩','subtitle' => '热搜榜','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}// 知乎热榜热度function zhihuHot(){$jsonRes = json_decode(Curl('https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true', null, null, "https://www.zhihu.com"), true);$tempArr = [];foreach ($jsonRes['data'] as $k => $v) {preg_match('/\d+/',$v['detail_text'], $hot);array_push($tempArr, ['index' => $k + 1,'title' => $v['target']['title'],'hot' => $hot . '万','url' => 'https://www.zhihu.com/question/' . urlencode($v['target']['id']),'mobilUrl' => 'https://www.zhihu.com/question/' . urlencode($v['target']['id'])]);}return ['success' => true,'title' => '知乎热榜','subtitle' => '热度','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}// 微博 热搜榜function wbresou(){$_md5 = md5(time());$cookie = "Cookie: {$_md5}:FG=1";$jsonRes = json_decode(Curl('https://weibo.com/ajax/side/hotSearch', null, $cookie, "https://s.weibo.com"), true);$tempArr = [];foreach ($jsonRes['data']['realtime'] as $k => $v) {array_push($tempArr, ['index' => $k + 1,'title' => $v['note'],'hot' => round($v['num'] / 10000, 1) . '万','url' => "https://s.weibo.com/weibo?q=" . $v['note'] . "&Refer=index",'mobilUrl' => "https://s.weibo.com/weibo?q=" . $v['note'] . "&Refer=index"]);}return ['success' => true,'title' => '微博','subtitle' => '热搜榜','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}// 百度热点 指数function baiduredian(){$_resHtml = str_replace(["\n", "\r", " "], '', Curl('https://top.baidu.com/board?tab=realtime', null));preg_match('/<!--s-data:(.*?)-->/', $_resHtml, $_resHtmlArr);$jsonRes = json_decode($_resHtmlArr, true);$tempArr = [];foreach ($jsonRes['data']['cards'] as $v) {foreach ($v['content'] as $k => $_v) {array_push($tempArr, ['index' => $k + 1,'title' => $_v['word'],'desc' => $_v['desc'],'pic' => $_v['img'],'url' => $_v['url'],'hot' => round($_v['hotScore'] / 10000, 1) . '万','mobilUrl' => $_v['appUrl']]);}}return ['success' => true,'title' => '百度热点','subtitle' => '指数','update_time' => date('Y-m-d h:i:s', time()),'data' => $tempArr];}$_type = $_GET['enews'] ? $_GET['enews'] : '';switch ($_type) { case 'baidu': $_res = baiduredian(); break; case 'zhihu': $_res = zhihuHot(); break; case 'weibo': $_res = wbresou(); break; case 'bilihot': $_res = bilibili_hot(); break; case 'biliall': $_res = bilibili_rankall(); break; case 'douyin': $_res = douyin(); break; case 'sspai': $_res = sspai(); break; default: $_res = ['success' => false, 'message' => '参数不完整']; break;}echo json_encode($_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);以上代码命名为hot.php。那如请求百度的就是hot.php?enews=baidu
怎么与小编的不是一样的呢 ?因为小编的接口已经已经被伪静态了。其实get请求字段都是enews 顺便在发一个AI封装的自定义函数,只需要改下参数就可以了!其实这也就是封装为函数的好处优点。可以复用还是复用。易于维护修改 首先封装个上下文对话的函数
//构建AI对话上下文function chataicontext($context, $message) {$postData = [];if (!empty($context)) {$context = array_slice($context, -2);foreach ($context as $messageItem) {$userContent = str_replace("\n", "\\n", $messageItem);if (!empty($userContent)) {$postData['messages'][] = ['role' => 'user', 'content' => $userContent];}$systemContent = str_replace("\n", "\\n", $messageItem);if (!empty($systemContent)) {$postData['messages'][] = ['role' => 'system', 'content' => $systemContent];}}}$userMessage = RepPostStr($message);if (!empty($userMessage)) {$postData['messages'][] = ['role' => 'user', 'content' => $userMessage];}return $postData;}接下来封装个CUL的post与get请求的函数(因为百度那个鸟人非不按照套路出牌,非要搞个什么token拼接的)
//curl封装(post与get)function CurlRequest($postData = null, $method = 'POST', $appkey = null, $url = null) {$ch = curl_init();$headers = array();$headers[] = "Content-Type: application/json";if (isset($appkey)) {$headers[] = "X-DashScope-SSE: disable"; $headers[] = "Authorization: Bearer " . $appkey;}if ($method === 'GET') {if ($postData) {$queryString = http_build_query($postData);$url = $url . (strpos($url, '?') === false ? '?' : '&') . $queryString;}curl_setopt($ch, CURLOPT_HTTPGET, true);}elseif ($method === 'POST') {curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);} else {return array('error' => '不支持的请求方法: ' . $method);}curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);$response = curl_exec($ch);if (curl_errno($ch)) {$error = curl_error($ch);curl_close($ch);return array('error' => $error);}curl_close($ch);return $response;}准备工作都做完了,最后开始上干货。按照AI类别进行不同的请求方法
$message=RepPostStr($_POST['message']);$context = isset($_SESSION['context']) ? $_SESSION['context'] : [];switch ($_GET['enews']) { case 'baidu': // 百度 $post_tokendata = [ 'grant_type' => 'client_credentials', 'client_id' => 'hC6gfhtgyhyaQeXZ6pNL0', 'client_secret' => 'kGZcwuWgfhyrthytp5ArcZ5GwOSEqQ' ]; $query_str = http_build_query($post_tokendata); $tokendata = CurlRequest($query_str, 'POST', '', 'https://aip.baidubce.com/oauth/2.0/token'); $tokendata = json_decode($tokendata, true); $baiduapiurl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=".$tokendata['access_token']; $postData = ["top_p" => 0.9, "temperature" => 0.9]; $postData = array_merge($postData, chataicontext($context, $message)); // 百度角色调整也是个奇葩非不跟大家保持一致 foreach ($postData['messages'] as &$msg) { if ($msg['role'] ==='system') { $msg['role'] = 'assistant'; } } unset($msg); $postData = json_encode($postData); $response = CurlRequest($postData, 'POST', '', $baiduapiurl); $response = json_decode($response, true); if (isset($response['error_msg'])) { $aierrormsg = $response['error_msg']; } else { $text = $response['result']; } break; case 'aliyun': // 阿里云 $postData = ["model" => 'qwen-turbo', "enable_search" => true]; $postData = array_merge($postData, chataicontext($context, $message)); $postData = json_encode($postData); $response = CurlRequest($postData, 'POST', 'sk-97648484845d4d4793b974f091e0dbb746', 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'); $response = json_decode($response, true); if (isset($response['error']['message'])) { $aierrormsg = $response['error']['message']; } else { $text = $response['choices']['message']['content']; } break; case 'deepseek': // 深度求索 $postData = ["model" => 'deepseek-chat', "enable_search" => true]; $postData = array_merge($postData, chataicontext($context, $message)); $postData = json_encode($postData); $response = CurlRequest($postData, 'POST', 'sk-ea9gffyufyuu1b0cb8b97c9956ead', 'https://api.deepseek.com/v1/chat/completions'); $response = json_decode($response, true); if (isset($response['error']['message'])) { $aierrormsg = $response['error']['message']; } else { $text = $response['choices']['message']['content']; } break; default: // 豆包 $postData = ["model" => 'ep-20241215230414-l9zv8', "enable_search" => true]; $postData = array_merge($postData, chataicontext($context, $message)); $postData = json_encode($postData); $response = CurlRequest($postData, 'POST', '3668adyhjggka6d-09634418b9a3', 'https://ark.cn-beijing.volces.com/api/v1/chat/completions'); $response = json_decode($response, true); if (isset($response['error']['message'])) { $aierrormsg = $response['error']['message']; } else { $text = $response['choices']['message']['content']; } break;}仅供参考。注意前端AJAX请求的时候哈 我这个是已经支持返回的txt文本了 不是JSON。 现在才看到 里面有帝国的变量过滤函数,其他的CMS去掉即可 我也想这样 《PHP 开发:百度、阿里、深度求索与豆包 API 对接教程全解析》原创首发地址:
https://www.wenyunfang.com/zazhi/zhongwangjiaocheng/1254.html SSE流式输出就没有做了哈!毕竟大家用AI都是用来生成文章的并不是AI聊天的。这样可以大大方便对接火车头,彩票下期预测等方面。火车头在会捣鼓下,直接把接口的请求类型搞成数组,随机出来各大AI生成不同的文章。 原来是抄的哦! 你去抄 说个鸟话 牛逼!感谢老哥!
页:
[1]
2