php - 使用 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
解决方案
我想你可以尝试使用这个
$decoded=json_decode($response, true);
而不是这个
$decoded = json_decode($response);
它会将您转换stdClass
为数组。请注意,这$decoded
是数组,然后您可以根据需要使用。
用于var_dump($decoded)
调试对象
推荐阅读
- python - PyInstaller 生成的可执行文件中的 Python SSL 导入错误
- reactjs - 如何用阿波罗链接错误显示一个漂亮的错误
- laravel - 密码重置时应用了不需要的验证规则
- java - if / else的可选方式
- javascript - Safari/Iphone 弹跳效果在 JavaScript 代码中触发向下滚动功能,使导航栏消失
- java - getBackground() 在 android 中返回什么?
- vue.js - npm run serve 在运行时卡在 40%
- active-directory - ObjectClass=user 和 (&(sAMAccountType=805306368)(sAMAccountName=userName)) 有什么区别?
- r - 如何使用 plotly subplots() 删除重复的图例条目
- java - 如何从android java中的另一个活动访问asyntask的返回值