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"
}