M. Dmitriev M. Dmitriev - 7 months ago 13
PHP Question

Why I can't decode and parse user friends in json?

Here is code:

<?php
$userFriends = json_decode(file_get_contents("http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=[api-key]&steamid=[steam-id]&relationship=all"), true);
foreach ($userFriends->data as $friend) {
//$json = json_decode(file_get_contents("http://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=".rawurlencode($item)), true);
echo $friend->friends;
}
?>


Can't parse. Where problem?

Answer

First of all, if you want access to JSON data with oo -> syntax, you have to remove True parameter from json_decode:

$userFriends = json_decode( file_get_contents( ... ), true );

Then, your JSON has this structure:

{
    "friendslist": {
        "friends": [
            {
                "steamid": "0123456789",
                "relationship": "friend",
                "friend_since": 0
            },
            (...)
        ]

    }
}    

So, to access to friends, you have to write something like this:

foreach( $userFriends->friendslist->friends as $friend )
{
    echo $friend->steamid . PHP_EOL;
    echo $friend->relationship . PHP_EOL;
    echo $friend->friend_since . PHP_EOL;
}