PHP curl后json_decode无法将json转换成数组(转)

整了嗯久,PHP curl后json_decode无法将json转换成数组;最后才得到原因:

curl返回的数据中带有bom格式,需要转换;

有些返回数据直接:

print_r(json_decode($data,true)); 

就可以转换。

        $url = "http://localhost/web_services.php";
        $post_data = array ("username" => "bob","key" => "12345");
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);// post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回    
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回  
        $output = curl_exec($ch);
        curl_close($ch);//打印获得的数据
        print_r($output); 
        
        
        得到数据:
        {"code_img_url":"https:\/\/pay.swiftpass.cn\/pay\/qrcode?uuid=https%3A%2F%2Fqr.alipay.com%2Fbax00722bbvbiqp1yp3960a6","code_url":"https:\/\/qr.alipay.com\/bax00722bbvbiqp1yp3960a6"}
        
        转换:
        if(preg_match('/^\xEF\xBB\xBF/',$output))  
        {  
            $output = substr($output,3);  
        }  
        $info = json_decode(trim($output),true);  
        
        print_r($info); 
        
        array(2) {
          ["code_img_url"] => string(95) "https://pay.swiftpass.cn/pay/qrcode?uuid=https%3A%2F%2Fqr.alipay.com%2Fbax00722bbvbiqp1yp3960a6"
          ["code_url"] => string(46) "https://qr.alipay.com/bax00722bbvbiqp1yp3960a6"
        }

猜你喜欢

转载自blog.csdn.net/changemust/article/details/81128289
今日推荐