[英]Trying to get property of non-object error PHP curl
Im trying to use an api to get a fruit information.我试图使用 api 来获取水果信息。
$fruitStirng = 'apple';
$url = "https://www.fruityvice.com/api/fruit/".$fruitStirng;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$main = json_decode($res);
Result should be something like this:结果应该是这样的:
{ "genus": "Malus", "name": "Apple", "id": 6, "family": "Rosaceae", "order": "Rosales", "nutritions": { "carbohydrates": 11.4, "protein": 0.3, "fat": 0.4, "calories": 52, "sugar": 10.3 } }
but for example when im trying echo genus
like this:但例如当我尝试像这样的回声
genus
时:
$genus = $main->genus;
echo $genus
I get Trying to get property 'genus' of non-object
error !我得到
Trying to get property 'genus' of non-object
!
I also used foreach but got an error too我也使用了foreach,但也出现了错误
Invalid argument supplied for foreach()
Since API returning the JSON uses HTTPS, you must configure cURL SSL option (CURLOPT_SSL_VERIFYPEER). Since API returning the JSON uses HTTPS, you must configure cURL SSL option (CURLOPT_SSL_VERIFYPEER). Here's a working code:
这是一个工作代码:
<?php
$fruitString = 'apple';
$url = "https://www.fruityvice.com/api/fruit/".$fruitString;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$main = json_decode($res);
$genus = $main->genus;
echo $genus; // Malus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.