前言
本文章所使用的接口地址为https://www.juhe.cn/docs/api/id/235
本文章的所有代码都是现使用代码,就是说,我的接口也是用这个代码的,所以代码可以正常使用。
我的接口文档doc.berfen.com(正在更新更多接口及文档)
下面直接上代码,各位可根据业务逻辑简单修改本篇代码。
代码
<?php
error_reporting(0);//关闭报错,生产环境下可以开启
function curl($data)
{
$url = 'http://v.juhe.cn/toutiao/index';
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
return $return;
}
function revert($data, $code = 200, $msg = '')
{
header('Content-type:text/json; charset=utf-8');
echo json_encode(array(
'data' => $data,
'code' => $code,
'msg' => $msg
), JSON_UNESCAPED_UNICODE);
exit();
}
// 支持的新闻类型
$new_type_list = array(
'top',
'shehui',
'guonei',
'guoji',
'yule',
'tiyu',
'junshi',
'keji',
'caijing',
'shishang'
);
//开发者KEY
$app_key = '后台查看';
$type = $_REQUEST['type'];
if (isset($type)) {
if (!in_array($type, $new_type_list))
revert('', 401, '新闻类型错误');
$url_data = array(
"key" => $app_key,
"type" => $type
);
$obtain = curl($url_data);
if ($obtain['error_code'] == 0) {
$obtain_arr = json_decode($obtain, true);
$obtain_result = $obtain_arr['result'];
foreach ($obtain_result['data'] as $data) {
$title = $data['title'];//新闻标题
$time = $data['date'];//发布时间
$new_type = $data['category'];//新闻类别
$author = $data['author_name'];//发布者名称
$new_url = $data['url'];//新闻链接
$new_cover = $data['thumbnail_pic_s'];//新闻的第一张封面,可参考今日头条的列表
$new_cover_2 = $data['thumbnail_pic_s02'];//新闻的第二张封面,有的新闻没有,所以请自行在业务代码里进行判断
$new_cover_3 = $data['thumbnail_pic_s03'];//新闻的第三张封面,有的新闻没有,所以请自行在业务代码里进行判断
$content[] = array(
'title' => $title,
'time' => $time,
'new_type' => $new_type,
'author' => $author,
'url' => $new_url,
'cover' => $new_cover,
'cover_2' => $new_cover_2,
'cover_3' => $new_cover_3
);
}
revert($content, 200, '');//成功返回
} else {
revert('', 500, '服务器错误,具体错误代码为' . $obtain['error_code']);
}
} else {
revert('', 404, '请输入新闻类型');
}
?>