jack Bourke-Mckenna
jack Bourke-Mckenna

Reputation: 141

Trying to get data from json api

I'm working on a very small project. I am trying to pull "name": "PHP", from this json response but I'm quite confused on how to go about this. This is the json:

"request": "https://whatcms.org/APIEndpoint/Technology?key=hidden&url=en.wikipedia.org",
"request_web": "https://whatcms.org/?s=en.wikipedia.org",
"result": {
    "code": 200,
    "msg": "Success"
},
"results": [
    {
        "categories": [
            "Wiki"
        ],
        "name": "MediaWiki",
        "url": "https://whatcms.org/c/MediaWiki",
        "version": "1.34.0"
    },
    {
        "categories": [
            "Programming Language"
        ],
        "name": "PHP",
        "version": ""
    },
    {
        "categories": [
            "Web Server"
        ],
        "name": "HHVM",
        "version": "3.18.6"
    }
]

}

This is the code I tried but does not seem to work. I get this error Notice: Trying to get property 'name' of non-object

$data = file_get_contents($url);
$categories = json_decode($data);
$output =  $categories->results->name;
echo $output;

I'm quite new to php and json so I'm not quite sure what I am doing. Any help would be great, thanks.

Upvotes: 1

Views: 37

Answers (1)

atymic
atymic

Reputation: 3128

Your code isn't working because $categories->results isn't an object, but an array.

You can access the name of the first object in the array like so:

$categories->results[0]->name;

If you wanted to get all of the names, you could loop or map over the array:

array_map(function ($category) {
    return $category->name;
}, $categories->results);

Upvotes: 1

Related Questions