【#第一文档网# 导语】以下是®第一文档网的小编为您整理的《新浪微博API中返回的中文表情转成相应图片的PHP代码》,欢迎阅读!
新浪微博API中返回的中文表情转成相应图片的PHP代码
通过新浪微博API的http://api.t.sina.com.cn/statuses/home_timeline.json的接口获取列表后,内容中的表情只是文字,如[哈],[神马],[浮云],[给力]等等,我们需要转成图片,下面具体说明
第一步:读取表情列表,缓存本地
新浪微博表情API地址:http://api.t.sina.com.cn/emotions.json 直接在 class WeiboClient 中添加一个自定义函数 function get_emotions(){
$url="http://api.t.sina.com.cn/emotions.json"; return $this->oauth->get($url); }
表情列表函数
function get_wb_face($c){
if( !is_file('缓存地址/wbface.php')){
$face_arr = $c->get_emotions(); // 远程获取表情列表 $cachefile = "缓存地址/wbface.php"; $arr = array();
foreach($face_arr as $val){
$arr[$val['phrase']] = ''; }
$cachetext = " '$face='.arrayval($arr). '\r\n?>';
if(@fp= fopen($cachefile,'w')){ flock($fp,2);
fwrite($fp ,$cachetext); fclose($fp); } } }
function arrayeval_r($array, $level = 0) { $space = '';
for($i = 0; $i <= $level; $i++) { $space .= "\t"; }
$evaluate = "Array\n$space(\n"; $comma = $space;
foreach($array as $key => $val) {
$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
$val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12 || substr($val, 0, 1)=='0') ? '\''.addcslashes($val, '\'\\').'\'' : $val; if(is_array($val)) {
$evaluate .= "$comma$key => ".arrayeval_r($val, $level + 1); } else {
$evaluate .= "$comma$key => $val"; }
$comma = ",\n$space"; }
$evaluate .= "\n$space)";
return $evaluate; }
最后生成的效果图
缓存中文表情和表情图片的数组 缓存中文表情和表情图片的数组 第二步:替换内容中的文字为表情 部分代码:
// 省略前面代码.....
$wb_list_arr=$c->home_timeline($page,$count);//微博列表 get_wb_face($c);
include_once '缓存地址/wbface.php'; foreach( $wb_list_arr as $key=>$val){
$str= strtr($val['text'],$face);//其中$face就是第一步生成的一个缓存变量 $str = eregi_replace('(((f|ht){1}tp://t.cn/)[a-zA-Z0-9]+)','target="_blank">\1',$str);// 超链替换 $wb_list_arr[$key]['text']=$str;
if($val['retweeted_status']){//转载中的内容
$str = strtr($val['retweeted_status']['text'],$face);// 图标
//$str = eregi_replace('(((f|ht){1}tp://t.cn/)[a-zA-Z0-9]+)','target="_blank">\1',$str);// 超链替换
$wb_list_arr[$key]['retweeted_status']['text'] = $str; } }
die(json_encode($wb_list_arr));//json格式输出 最后看看生成的效果截图吧
http://softuses.com/sina-api-chineseface-to-icon-php-code
本文来源:https://www.dy1993.cn/n9qG.html