给自己的Blog加了“最近”功能
作者:Qianfeng 发布时间:September 3, 2010 分类:PHP,JS,.net,SQL@Develop
就是通过豆瓣API,获取我在豆瓣的一些信息,就可以看到我最近看的电影和书了。
豆瓣API,一般用户有访问次数限制,因为我只是要我自己的信息,所有使用很简单的php文件缓存,避免读取访问太多次后获取不到数据…同时减少了我VPS的流量,也降低了豆瓣API的压力,哈哈。当然,这样其实完全可以不需要豆瓣apikey就能应付了(没有apikey每分钟10次请求,有apikey每分钟40次请求)。
第一次使用在php里使用json,json_decode后会出现一些奇怪的属性名,例如:“db:subject”,“db_status”,“$t”,“@href”等,解决办法很简单,使用一个变量保存着它,例如 $name='db:subject'; 然后直接$data->$name就可以访问了!
我是通过添加页面,设置模板来实现。下面是代码,只有到获取数据到$douban_data,需要的话可以print_r($douban_data);查看结构,很简单……
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <?php $DOUBAN_KEY = '你的apikey'; $DOUBAN_USERID = '你的UserId'; $DOUBAN_DB = 'db:subject'; //json_decode后的特殊属性名 $DOUBAN_STATUS = 'db:status'; //json_decode后的特殊属性名 $DOUBAN_TITLE = '$t'; //json_decode后的特殊属性名 $DOUBAN_HREF = '@href'; //json_decode后的特殊属性名 $douban_cache_file_path = dirname(__FILE__) . '/' . 'douban_cache.php'; //豆瓣数据缓存文件地址 $douban_cacle_lifetime = 60; //缓存生存时间 $cats = array ( 'book', 'movie' ); //只要两个分类的 $sataus = array ( 'wish' => '想看', 'read' => '看过', 'reading' => '在看', 'watched' => '看过' ); //状态的中英文对应 $douban_data = array (); if (is_file($douban_cache_file_path)) {//缓存文件存在 $douban_data = include ($douban_cache_file_path); //读取缓存数据 if (is_array($douban_data) && isset($douban_data['expired']) && $douban_data['expired'] > time()) { //数据是数组且有过期时间且未过期 $douban_data = $douban_data['data']; } else { //否则设置为空数组 $douban_data = array (); } } if (count($douban_data) < 1) //没有缓存 { //数据总数小于1则没有缓存数据或已经过期 foreach ( $cats as $cat ) { //遍历所有分类 $data = file_get_contents("http://api.douban.com/people/{$DOUBAN_USERID}/collection?cat={$cat}&alt=json&start-index=0&max-results=8&apikey={$DOUBAN_KEY}"); //获取数据 $data = json_decode($data); //json转换成对象/数组 $douban_data["{$cat}s"] = array (); foreach ( $data->entry as $_subject ) { //变量所有对象 $subject = array (); $subject['img'] = $_subject->$DOUBAN_DB->link[2]->$DOUBAN_HREF; //获取图片地址 $subject['link'] = $_subject->$DOUBAN_DB->link[1]->$DOUBAN_HREF; //获取连接地址 $subject['title'] = $_subject->$DOUBAN_DB->title->$DOUBAN_TITLE; //获取标题 $subject['status'] = $sataus[$_subject->$DOUBAN_STATUS->$DOUBAN_TITLE]; //获取状态 $douban_data["{$cat}s"][] = $subject; //存进douban_data } } $expired = time() + $douban_cacle_lifetime; //过期时间,现在时间戳+生存时间 $douban_cache_content = array ( 'expired' => $expired, 'data' => $douban_data ); //缓存内容格式 $douban_cache_content = '<?php return ' . var_export($douban_cache_content, true) . ';'; // 写入缓存 file_put_contents($douban_cache_file_path, $douban_cache_content, LOCK_EX); } ?> |
你好。我发现你的网站通过谷歌寻找类似的问题时,您的网站来到这里。看来不错。我已经在我的Google书签书签回来后。
想问一下,如果是xml的话那么db:subject应该怎么处理呢?也是像json一样定义一个$douban_statues就好了么?我试了试,貌似不可以,求教一下~ :-P
[...] Example 1 This entry was written by 牛司机 and posted on December 7, 2010 at 4:13 pm and filed under Programming. Bookmark the permalink. Follow any comments here with the RSS feed for this post. [...]