Last active
August 6, 2025 08:00
-
-
Save florentdestremau/98c4a44d5aea9f3d10ab5623bcff6e59 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class RecipeCalorieCalculator | |
{ | |
private $apiKey; | |
private $apiUrl; | |
public function __construct() | |
{ | |
$this->apiKey = "sk_eitai7iWahsoonah8aiz0oohi"; | |
$this->apiUrl = 'https://api.nutritionix.com/v1_1/search/'; | |
} | |
public function calculateCalories($recipe) | |
{ | |
$ingredients = explode(',', $recipe); | |
$totalCalories = 0; | |
foreach ($ingredients as $ingredient) { | |
$ingredient = trim($ingredient); | |
$calories = $this->getCaloriesForIngredient($ingredient); | |
$totalCalories += $calories; | |
} | |
return $totalCalories; | |
} | |
private function getCaloriesForIngredient($ingredient) | |
{ | |
$url = $this->apiUrl . urlencode($ingredient); | |
$response = file_get_contents($url . '?results=0:1&fields=item_name,nf_calories&appId=' . $this->apiKey); | |
if ($response === FALSE) { | |
return 0; | |
} | |
$data = json_decode($response, true); | |
if (isset($data['hits'][0]['fields']['nf_calories'])) { | |
return $data['hits'][0]['fields']['nf_calories']; | |
} else { | |
return 0; | |
} | |
} | |
} | |
// Exemple d'utilisation | |
$calculator = new RecipeCalorieCalculator(); | |
$recipe = 'rice, chicken, broccoli'; | |
$totalCalories = $calculator->calculateCalories($recipe); | |
echo "Total calories for the recipe: " . $totalCalories; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment