天使漫步IT工作室天使漫步IT工作室

curl_exec 返回值无法json_decode的解决办法


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

php发起http请求的示例代码如下:

public function http_post2($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'X-AjaxPro-Method:ShowList',
        'Content-Type: application/json; charset=utf-8',
        'Content-Length: ' . strlen($data_string))
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

当尝试json_decode的时候,无法得到数据,原因是:curl返回的数据中带有bom格式,需要转换。

使用下面的代码可以将bom格式的字符串去掉,代码示例如下:

if(preg_match('/^\xEF\xBB\xBF/',$ret))
            {
                $ret = substr($ret,3);
            }
            $ret_data = json_decode(trim($ret),true);

建议封装成函数,放到library库里面使用。

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » curl_exec 返回值无法json_decode的解决办法
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38