1

I have the following code that i am trying to get the jSON contents from;

$url = "http://useragentapi.com/api/v3/json/APIKEY/$ua";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My Platform: ". $json_data["data.platform_name"];

I need to get inside of the data then to platform_name well i need to access all elements of the JSON object but i can get the code to work.

The JSON result [$json_data] is this.

{
"data": {
        "platform_name": "Mac OSX El Capitan",
        "platform_version": "Mac OS X 10_11",
        "platform_type": "Desktop",
        "browser_name": "Chrome",
        "browser_version": "52.0.2718.0",
        "engine_name": "WebKit",
        "engine_version": "537.36"
        }
}
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
Liam Armour
  • 119
  • 1
  • 9

2 Answers2

3

try this:

$json = '{
"data": {
        "platform_name": "Mac OSX El Capitan",
        "platform_version": "Mac OS X 10_11",
        "platform_type": "Desktop",
        "browser_name": "Chrome",
        "browser_version": "52.0.2718.0",
        "engine_name": "WebKit",
        "engine_version": "537.36"
        }
}';

Decode the json using json_decode function and use second parameter as true for getting the associative array as output.

$arr = json_decode($json, true);

Result

Array
(
    [data] => Array
        (
            [platform_name] => Mac OSX El Capitan
            [platform_version] => Mac OS X 10_11
            [platform_type] => Desktop
            [browser_name] => Chrome
            [browser_version] => 52.0.2718.0
            [engine_name] => WebKit
            [engine_version] => 537.36
        )

)

echo $arr['data']['platform_name'];

Output:

Mac OSX El Capitan

If you don't use the true as second parameter of json_decode then you have to do this:

$arr = json_decode($json);

echo $arr->data->platform_name; //Mac OSX El Capitan
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
1

Try This

$json = '{
    "data": {
    "platform_name": "Mac OSX El Capitan",
    "platform_version": "Mac OS X 10_11",
    "platform_type": "Desktop",
    "browser_name": "Chrome",
    "browser_version": "52.0.2718.0",
    "engine_name": "WebKit",
    "engine_version": "537.36"
    }
}';


$arr = json_decode($json);
echo $arr->data->platform_name;
Vinie
  • 2,983
  • 1
  • 18
  • 29