【发布时间】:2018-06-13 06:06:07
【问题描述】:
我正在尝试学习从 API 检索数据。我正在访问需要 POST 的 API,因此我使用 cURL:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "api-url-here",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "api_key=myapikey&format=json&logs=1&search=mykeyword", "method=JSON",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
到目前为止一切顺利。
如果我回显$response,我会得到我正在搜索的关键字的 JSON 结果。但是如何从它们的结果中获取单个元素?
我尝试使用json_decode($response),但出现此错误:
Catchable fatal error: Object of class stdClass could not be converted to string
【问题讨论】:
-
请分享您从 API 收到的
$response文本 -
{"stat":"ok","pagination":{"offset":0,"limit":50,"total":1},"monitors":[{"id" :780536830,"friendly_name":"Bangkokguide","url":"bangkokguide.dk/… om Bangkok","http_username":"","http_password":"","port":"","interval":1800, "status":2,"ssl":{"brand":"","product":null,"expires":0},"create_datetime":1528321171,"logs":[{"type":2," datetime":1528317598,"duration":552970,"reason":{"code":"999999","detail":"Keyword Found"}},{"type":98,"datetime":1528317561,"duration ":37,"reason":{"code":"98","detail":"监控开始"}}]}]}
-
使用
json_decode($response,true)。打印时不使用echo使用var_dump或var_export -
这只是您所问内容的建议。您可以尝试Guzzle 进行 API 调用。