我正在为来自curl_exec
json GET请求的每个结果创建div。我已经在PHP中使用cURL尝试了以下代码。当我运行这段代码时,foreach
一无所有。
//API Url
$url = 'https://api.clover.com:443/v3/merchants/'.$merchantid.'/categories/';
//Initiate cURL.
$ch = curl_init($url);
$headers = array(
'Content-type: application/json',
'Authorization: Bearer '.$authtoken.' ',
);
//Tell cURL that we want to send a GET request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Execute the request
$resp = curl_exec($ch);
$respArray = json_decode($resp, true);
foreach($respArray as $key => $value) {
echo $key . " : " . $value;
}
curl_close($ch);
这将返回以下内容:
{
"elements": [
{
"id": "QWS8MSMAT49E6",
"name": "Other",
"sortOrder": 2
},
{
"id": "35K000MJVVFHE",
"name": "Pizza",
"sortOrder": 1
}
],
"href": "http://api.clover.com/v3/merchants/{[MID]}/categories?limit=100"
}
我正在尝试将上面的信息放入div中,例如:
答案 0 :(得分:0)
认为它是这样的:
$data = json_decode($resp);
foreach($data->elements as $element) {
echo '<div id="group_'.$element->id.'" class="product_group">'.$element->name.'</div>';
}
答案 1 :(得分:0)
我已经解决了添加
的问题curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
到代码。正如已经解释过的Here (by Mihai)
“ 默认情况下,curl_exec将从服务器获取的数据输出到 标准输出,因此您的$ response变量实际上没有 实际的响应数据。如果要获取变量中的数据 在调用curl_exec之前设置CURLOPT_RETURNTRANSFER选项。“
Martin Zeitler's的正确答案是从true
中删除json_decode()