我创建的函数名是getURLContent。 Curl返回数据的json数据示例是:
{"request":{"method":"GET","version":"v1","product":"cloud","route":"project","func":"checkCJIsBusy"},"response":[{"id":2000858,"status":3},{"id":2000859,"status":7}]}
数据被解码。返回的数据是stdclass对象。我想打印id的值。我能怎么做?
function getURLContent($url, $method = "GET", $params = NULL, $timeout = 60) {
if (strtoupper($method) == "GET" && $params) $url .= "?" . $params;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (strtoupper($method) == "POST") {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params != NULL ? $params : "");
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
$chError = curl_error($ch);
curl_close($ch);
return json_decode($data);
}
$result=getURLContent($url);
print_r($result);
结果是print_r
stdClass Object ( [request] => stdClass Object ( [method] => GET [version] => v1 [product] => dwgcloud [route] => project [func] => checkCJIsBusy ) [response] => Array ( [0] => stdClass Object ( [id] => 2000858 [status] => 3 ) [1] => stdClass Object ( [id] => 2000859 [status] => 7 ) [2] => stdClass Object ( [id] => 2000860 [status] => 7 ) ) )
答案 0 :(得分:1)
试试这段代码:
foreach ($result->response as $value){
echo $value->id;
echo "<br>";
}
答案 1 :(得分:1)
此方法将已解码的json转换为关联数组。
<?php
$json_string = '{"request":{"method":"GET","version":"v1","product":"cloud","route":"project","func":"checkCJIsBusy"},"response":[{"id":2000858,"status":3},{"id":2000859,"status":7}]}';
$result = json_decode($json_string,true);
foreach ($result["response"] as $value) {
print_r($value["id"]);
print_r("\n");
}