3

So I'm doing a project for college involving an API for information about food, it returns the food brand, id, energy and fat etc.. via JSON, it also returns lots of other information that I don't want via JSON so I'm wondering how I can be selective with what I return and then use.

I'm connecting to the API using PHP and this is the code I'm using.

<?php
//$ingr = "ingr=" . $_GET['foodName'];
$ingr = "ingr=Bread";

//echo getFoodFromAPI($ingr);
getFoodFromAPI($ingr);

//return $decodedData;
function getFoodFromAPI($ingr){
    /*$queryParams = array(
        'Food' => $JsonFood
    );*/
    //echo $JsonFood;
    $api = "https://api.edamam.com/api/food-database/parser?";
    $apiId = "&app_id=ABC";
    $apiKey = "&app_key=ABC";
    $url = $api . $ingr . $apiId . $apiKey; //+ $search

    $JsonContents = file_get_contents($url);
    $Json = json_decode($JsonContents);

    //echo $JsonBrand."Hello There Brand";

    for ($x = 1; $x <= 10; $x++) {
        $JsonBrand = $Json->hints[$x]->{'food'}->{'brand'} . "<br>"; //used to echo the values of the decoded data
        $JsonLabel = $Json->hints[$x]->{'food'}->{'label'} . "<br>"; //used to echo the values of the decoded data
        echo $JsonBrand;
        echo $JsonLabel;
    } 

    $JsonRec = json_encode($Json);



    //print_r($JsonRec->hints->food);

    return $JsonRec;

};

?>

So my question is this, is there a way to return only certain parts of the JSON decode? I don't need/want certain information (eg: Return only the brand & id of the food) and also is there a way I can use the returned data being either a PHP object OR array in javascript (i.e show it to a client on a webpage)

Please feel free to ask me to clarify anything I've failed to explain, like I said I'm a college student so I'm still learning and grasping the languages as I use them.

Also for reference here is the HTML & JavaScript I was working with and again I don't know if this is correct either because there is a mix between AJAX and JQuery.

function find_food(foodName) {
  var vars = "foodName" + foodName;
  var result = "";

  $.ajax({
    url: "sendFood.php",
    type: "GET",
    data: vars,
    async: false,
    success: function(data) {
      console.log(data + "Data Here !");
      result = data;
    }
  });
  return result;
  //console.log(result);
  //return result;
}

function searchFoodDic() {
  var food = document.getElementById("foodName").value;
  console.log(food);
  //var htmlText = "";
  document.getElementById("searchedFood").innerHTML = "processing...";
  var foodSearched = find_food(food);
  console.log('>>>> searched food: ', foodSearched);
  //htmlText += '<p class="p-name"> Train Code: ' + foodSearched[1].brand + '</p>';
  //var filteredFood = getCommonFoods(foodSearched.food);
  //console.log('>>>> filtered food: ', filteredFood);
  htmlText = "Hello";

  for (i = 0; i < 5; i++) {
    //htmlText += '<p class="p-foodName"> Food Name: ' + data.hints[i].food.brand + '</p>';
    htmlText += '<p class="p-foodLabel1"> Food Label 1: ' + foodSearched.foodId + '</p>';
    htmlText += '<p class="p-foodLabel2"> Food Label 2: ' + foodSearched.label + '</p>';
    htmlText += '<br/>';
  }

  document.getElementById("searchedFood").innerHTML = htmlText;
}
<link rel="stylesheet" type="text/css" href="food.css">
<html>

<head>
  <ul>
    <li><a class="active" href="index.php">Home </a></li>
    <li><a href="admin.html">Administration</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


</head>
<title> Food Website </title>

<body>
  <script src="searchFood.js" type="text/javascript"></script>
  <div class="food-container">
    <input type="text" id="foodName" name="foodName" placeholder="Enter food eg: Apple, Bread">
    <input type="submit" onclick="searchFoodDic()">
    <div id="searchedFood">

    </div>
  </div>
</body>

</html>

6
  • No you can't selectively decode parts of a JSON string (not native-ly anyway, and if there was you'd have more processing to strip out the stuff you didn't want), so just ignore what you don't need. I'm not really sure what the second part is getting at. If you have the data in PHP, of course you can output that data to the page in whatever format you want, JSON being the most used one in my experience when returning data to JavaScript.
    – Jonnix
    Commented Dec 2, 2018 at 23:04
  • Please keep questions unambiguous and open a second one for a second question 😉
    – Matthi
    Commented Dec 2, 2018 at 23:12
  • Ok that's good information to know thanks Jon, do you know of any guides or anything I can read or watch that show how you use the returned JSON data in JavaScript because using the returned data in the way I want to is the the problem I think I'm facing. Commented Dec 2, 2018 at 23:13
  • Since you're using jQuery, my suggestion is to read their docs.
    – Jonnix
    Commented Dec 2, 2018 at 23:18
  • @JonStirling That's not true... there are streaming JSON parsers built for exactly this purpose! (Of course, this particular situation doesn't require one.)
    – Brad
    Commented Dec 2, 2018 at 23:34

1 Answer 1

2

You can create a new array of the data you want to return to the JS. For example, inside your function you could change your code to look like this

$Json = json_decode($JsonContents);
$output = [];

for ($x = 1; $x <= 10; $x++) {
    $hint = [];
    $hint['brand'] = $Json->hints[$x]->{'food'}->{'brand'};
    $hint['label'] = $Json->hints[$x]->{'food'}->{'label'};
    $output[] = $hint;
}

return $output;

You can then return this data like so

echo json_encode(getFoodFromAPI($ingr));

Your JS would look like this:

foodSearched.forEach(function(hint) {
    console.log('Brand is ' + hint.brand + ' and label is ' + hint.label);
});

You are close to achieving your goal, you just need to return only the 'broken down' data of the API request to the JS HTTP request. At the moment, you are doing the correct PHP logic of breaking down only the data you want to return to the JS, but you are using $JsonRec = json_encode($Json); which is sending back all of the API request rather than your PHP logic.

Hope this helps.

Here is a working example for you to just test

# Eggs
$response = json_decode(file_get_contents('https://api.edamam.com/api/food-database/parser?ingr=egg&app_id=47971bbd&app_key=15ddd5fb6a552c59762e2dc7093d5f85'));

$output = [];

for ($x = 1; $x <= 10; $x++) {
    $hint = [];
    $hint['brand'] = $response->hints[$x]->{'food'}->{'brand'};
    $hint['label'] = $response->hints[$x]->{'food'}->{'label'};
    $output[] = $hint;
}

header('Content-Type: application/json');
var_dump(json_encode($response)); # Here is what your JS would see
die();
13
  • Wow that was really helpful thank Jaquarh, I'm getting an error in my Javascript stating that foodSearched.forEach isn't a function. Should I be using a different function in my case? Commented Dec 2, 2018 at 23:43
  • 1
    Console.log(foodSearched) and make sure it is an array - I was using jQuery when I answered this so you may jus have to loop through manually using the foodSearched.length
    – Jaquarh
    Commented Dec 2, 2018 at 23:46
  • So I got the forEach function working but it's like all the data from my php is being stored at one index, I have the PHP and JS incrementing correctly from what I can see. Would I need to increment the foodSearched index since that's now an array? I also can't use the . modifier like you do for you forEach loop. Commented Dec 3, 2018 at 1:13
  • 1
    I actually don’t know why it isn’t working for you, do you have header(‘Content-Type: application/json’); before you use json_encode() ? If you do then i have no clue why its behaving like that, maybe another question on SO so we can see the code you have because mine works when I try it on localhost
    – Jaquarh
    Commented Dec 3, 2018 at 20:51
  • 1
    So with a little tinkering with the array in my JavaScript I got your solution from above working, thanks Jaquarh! Commented Dec 3, 2018 at 23:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.