Search code examples
phpjsonreddit

Reddit json and PHP - opening foreach() and getting values


I am trying to read a reddit json using my account as an example.

Tried the solution above as:

$string_reddit = file_get_contents("https://www.reddit.com/user/joshfolgado/about.json");

$json = json_decode($string_reddit, true);  

$children = $json['data'];
foreach ($children as $child){

$linkkarma = $child['data']['link_karma'];

}

Also tried:

foreach ($json->data as $mydata){

$values["Latest_Karma"] = $mydata['link_karma'];

}

Also tried:

$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"User-Agent: reddiant api script\r\n"
));

$context = stream_context_create($opts);
$url = "http://www.reddit.com/user/joshfolgado/about.json";
$json = file_get_contents($url, false, $context);

$result = json_decode($json, true);

foreach ($result as $child){
    $values['Latest_Karma'] = $child['data']['link_karma'];
}

Spent a couple of hours trying do get the values for any of the items inside the "data" array, havent been able to get any.

What am I doing wrong? What am I missing?

Any help is appreciated.

Thanks


Solution

  • A slight modification to pee2pee's post (His returned an undefined index error for me)

    $string_reddit = file_get_contents("http://www.reddit.com/user/joshfolgado/about.json");
    $json = json_decode($string_reddit, true);
    
    $children = $json['data'];
    $user = [];
    
    foreach ($children as $key => $value)
    {
        $user[$key] = $value;
    }
    
    echo $user['name']; //Now you can use the $user array to access all the properties!
    

    This works for me ->

    enter image description here