【问题标题】:Using cURL to access JSON from API [duplicate]使用 cURL 从 API 访问 JSON [重复]
【发布时间】: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_dumpvar_export
  • 这只是您所问内容的建议。您可以尝试Guzzle 进行 API 调用。

标签: php json api curl


【解决方案1】:

我觉得你可以试试这个

$decoded=json_decode($response, true);

而不是这个

$decoded = json_decode($response);

它将您的stdClass 转换为数组。注意$decoded是数组,你可以根据需要使用。

使用var_dump($decoded)调试对象

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2015-08-20
    • 2018-06-26
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多