将JSON数据转换为对象或数组

时间:2017-05-26 10:56:52

标签: php json

我正在尝试从URL中获取内容,并提供以下结果。问题是我无法将其转换为数组或对象。我已经检查了类似的其他查询并尝试了它们但我不明白为什么没有这样做!

[{
"Coupon_ID": "IW12390",
"Campaign_ID": "353",
"Campaign_Name": "Dominos",
"Title": "Get 10% Off on INR 400",
"Description": "Get 10% Off on INR 400 & Above. Valid for online order only. This code is not valid on Simply Veg, Simply N-Veg Pizzas, and Combos.",
"Category": "Food & Beverages",
"Type": "Coupon",
"Type_Value": "DOM10",
"Tracking_URL": "http:\/\/tracking.icubeswire.com\/aff_c?offer_id=353&aff_id=18753",
"Added_Date": "2017-02-01",
"Expiry_Date": "2017-02-07"
},{
"Coupon_ID": "IW12392",
"Campaign_ID": "2269",
"Campaign_Name": "Shoppers Stop",
"Title": "Flat 50% on Fratini Woman",
"Description": "Flat 50% on Fratini Woman only at Shoppers Stop. So Hurry!\r\n\r\n",
"Category": "E-Commerce",
"Type": "Deal",
"Type_Value": "None",
"Tracking_URL": "http:\/\/tracking.icubeswire.com\/aff_c?offer_id=2269&aff_id=18753&url_id=16740",
"Added_Date": "2017-01-05",
"Expiry_Date": "2017-02-01"
}]

我使用了以下curl方法将它们转换为上述数据,我还使用了file_get_contents,它提供了与上面相同的数据。我试图使用json_decode转换它,但结果为null。

$headers = array(
    "Content-Type: application/json"
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result ? $result : false;

3 个答案:

答案 0 :(得分:0)

$headers = array(
    "Content-Type: application/json"
);

$timeout = 30

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true)

答案 1 :(得分:0)

对于数组:json_decode($response, true);

对象:json_decode($response);

答案 2 :(得分:0)

json数据很长,大约有17839行。我无法追踪json_decode的错误,但错误是来自JSON API的格式错误的数据。它正在关闭},]。大括号之后的逗号是真正的问题,因为它没有被解码。