I'm accessing data from an API using json_decode. The code I have returns the array of ALL the date (see below), but I want to return specific data such as 'name' or 'locale'.
$json_string = 'http://api.duedil.com/open/search?q=Surfing%20Sumo&api_key=THE-API-KEY';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo '<pre>';
var_dump($obj);
This is what is returned (this is abbreviated to save space here):
array(1) {
["response"]=>
array(2) {
["pagination"]=>
string(79) "http://api.duedil.com/open/search?query=Duedil&total_results=6&limit=5&offset=5"
["data"]=>
array(5) {
[0]=>
array(4) {
["company_number"]=>
string(8) "06999618"
["locale"]=>
string(14) "United Kingdom"
["name"]=>
string(14) "Duedil Limited"
["uri"]=>
string(51) "http://api.duedil.com/open/uk/company/06999618.json"
}
You could just use
$name = $obj['response']['data'][0]['name'];
$locale = $obj['response']['data'][0]['locale'];
if you have multiple return values, you could loop over them
foreach ($obj['response']['data'] as $item) {
$name = $item['name'];
$locale = $item['locale'];
}
try this sample code:
<?php
$data = isset($obj['response']['data'])?$obj['response']['data']:FALSE;
if(is_array($data))
{
foreach ($data as $value) {
echo $value['name'];
echo $value['locale'];
}
}