2

Iam getting a json data from an API in the following format:

{"total":254,
 "countries":[  
 {  
  "name":"Zimbabwe",
  "code3":"ZWE",
  "code":"ZW"
 },
 {  
  "name":"Zambia",
  "code3":"ZMB",
  "code":"ZM"
  },
  {  
  "name":"Yemen",
  "code3":"YEM",
  "code":"YE"
  },
  {  
  "name":"XO",
  "code3":"XO ",
  "code":"XO"
  }
  }

This is my PHP Script to access the API data:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'api-key: 1234',
    'Content-Type: application/json',
    'Accept: application/json'
));     
curl_setopt ($curl, CURLOPT_URL, 'https://api.com/api/v3/countries');  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
$xml = curl_exec ($curl);  

if ($xml === false) {
    die('Error fetching data: ' . curl_error($curl));  
}
curl_close ($curl);  
echo htmlspecialchars("$xml", ENT_QUOTES);   
?>

How will i call the results in a table format or bootstrap format?

  • That data you receive is not in xml format, as your variable name seems to suggest, but in json format, just as you explicitly request in the http headers you sent. That means you have to `json_decode()` it first, then you can iterate over the `countries` array in a simple loop. – arkascha May 17 '18 at 07:03
  • Something like this..? $json_a = json_decode($xml, true); foreach ($json_a as $country => $countries) { echo $countries['name']; } –  May 17 '18 at 07:13
  • Iam getting an error after putting the above code: Notice: Undefined index: name –  May 17 '18 at 07:14
  • Can anyone pls help me on this. –  May 17 '18 at 07:16
  • Actually the json you posted is invalid... Are you sure that is exactly what you receive? – arkascha May 17 '18 at 07:23
  • Its a very long json data: Iam receiving the raw data in this format:"{"total":254,"countries":[{"name":"Zimbabwe","code3":"ZWE","code":"ZW"},{"name":"Zambia","code3":"ZMB","code":"ZM"},{"name":"Yemen","code3":"YEM","code":"YE"} –  May 17 '18 at 07:26
  • Ah, so you truncated it. You should have marked that in your question... Anyway, you need something like that: `$data->countries[1]['name']`, where `1` obviously is an example for the index of the entry you want to access in your loop. – arkascha May 17 '18 at 07:31
  • I am not getting. still let me try. Thank you. –  May 17 '18 at 07:35
  • and what if i need to access all the data. Can i do it in a foreach loop? –  May 17 '18 at 07:42
  • `$data = json_decode($json); foreach ($data->countries as $country) { echo $country['name']; }` – arkascha May 17 '18 at 08:09
  • Iam getting error when i added the code: Fatal error: Cannot use object of type stdClass as array. This line is having the error, echo $country['name']; –  May 17 '18 at 08:35
  • I Do apologize, I blindly copied your snippet... `$data = json_decode($json); foreach ($data->countries as $country) { echo $country->name; }` – arkascha May 17 '18 at 08:36
  • Thank you so much. its working very well now. :) –  May 17 '18 at 08:41

0 Answers0