Im trying to use an api to get a fruit information.
$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 = $main->genus;
echo $genus
I get Trying to get property 'genus' of non-object
error !
I also used foreach but got an error too
Invalid argument supplied for foreach()
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.