sun 发表于 2015-10-17 12:49:25

自定义API接口不得不提的那些事——害死人不偿命的BOM头

前两天用自定义的网站API写了个“今日头条”的微信模块,上传微擎0.6程序,安装后发现能正常通过CURL获取到通过json_encode产生的JSON数据,但json_decode后返回的居然是NULL。
由于微擎程序的调试带来的各种不方便,调试了两天程序之后,才发现是返回的JSON字符串中包含了不可见的BOM头!所以直接导致了json_decode的解码失败。
解决方法:用$result = json_decode(trim($contents,chr(239).chr(187).chr(191)),true); 去除BOM头不可见字符


接口程序如下:
<?php
//*****网 微信top10头条信息接口
//@author sun QQ 276572447
//www.ylsunyuan.com
//返回格式 JSON 包含BOM头不可见字符 json数组前必须用 $res = trim($res,chr(239).chr(187).chr(191));//去除BOM头
header("Content-type:text/html;charset=utf-8");
require("../e/class/connect.php");
require("../e/class/db_sql.php");
require("../e/data/dbcache/class.php");
$link=db_connect();
$empire=new mysqlquery();
$siteurl = "http://********.com";


$arr = array();
$query = "select newstime,title,titlepic,titleurl,smalltext from vod_ecms_video where isurl='0' and firsttitle='1'order by newstime desc limit 0,5";
$sql = $empire->query($query);


while($r = $empire->fetch($sql))
{
    $arr[] = $r;//把结果集合放到数组里
}
mysql_free_result($sql);//释放字符集


//格式化新数组
$res = array();
$i = 0;
foreach ($arr as $k => $v) {
    # code...

    $res[$i]['title'] = $v['title'];
    $res[$i]['description'] = $v['smalltext'];
    $res[$i]['picurl'] = $siteurl.$v['titlepic'];
    $res[$i]['newstime'] = $v['newstime'];
    $res[$i]['url'] = $siteurl.$v['titleurl'];
    $i++;

}



echo trim(json_encode($res));

微信模块如下:
<?php
/**
* 今日头条模块处理程序
*
* @author sun QQ 276572447
* @url http://www.ylsunyuan.com
*/
//header("Content-type:text/html;charset=utf-8");
defined('IN_IA') or exit('Access Denied');

class Sun_newsModuleProcessor extends WeModuleProcessor {
        public function respond() {
                $content = $this->message['content'];
                //这里定义此模块进行消息处理时的具体过程, 请查看微擎文档来编写你的代码

                $url = "http://**********/top10.php";        //返回格式 JSON 包含BOM头不可见字符 json数组前必须用 $res = trim($res,chr(239).chr(187).chr(191));//去除BOM头

                load()->func('communication');
                $res = ihttp_get($url);
                $res = $res['content'];

//$res = $this->trimall($res);

                $res = trim($res,chr(239).chr(187).chr(191));//去除BOM头
               
                $news = json_decode($res,ture);
               

                return $this->respNews($news);

        }


        public function trimall($str)//删除空格
        {
          $qian=array(" "," ","\t","\n","\r");
                 $hou=array("","","","","");
          return str_replace($qian,$hou,$str);      
        }
}

内容原创,转载请标明出外!
灵感信息来源:http://www.phpddt.com/php/json_decode-bom.html
文章出外:bbs.ylsunyuan.com官方网站:www.ylsunyuan.com
页: [1]
查看完整版本: 自定义API接口不得不提的那些事——害死人不偿命的BOM头