首页 > 解决方案 > 使用 cURL 从 API 访问 JSON

问题描述

我正在尝试学习从 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

标签: phpjsonapicurl

解决方案


我想你可以尝试使用这个

$decoded=json_decode($response, true);

而不是这个

$decoded = json_decode($response);

它会将您转换stdClass为数组。请注意,这$decoded是数组,然后您可以根据需要使用。

用于var_dump($decoded)调试对象


推荐阅读