0

Is there a simple way to display on my website a specific value, for example "Gonna make this my new alarm ringtone" from following reddit comments .json file: https://www.reddit.com/r/funny/comments/mi0lic/.json

I've found a simple php script that works with reddit user .json files:

... $content = file_get_contents("https://www.reddit.com/user/joshfolgado/about.json");
$result  = json_decode($content);
print_r( $result->data->subreddit->title ); ...

But I can't make this work using the comments .json file:

... $content = file_get_contents("https://www.reddit.com/r/funny/comments/mi0lic/.json");
$result  = json_decode($content);
print_r( $result->data->children->data->title ); ...

Any other simple script that does the job is also welcome.

ZygD
  • 22,092
  • 39
  • 79
  • 102
  • I found it might be better to use https://api.reddit.com/api/info/?id=t3_mi0lic instead to get rid of all a possible very long list of replies in a comment, so the script would look more like:...$content = file_get_contents("https://api.reddit.com/api/info/?id=t3_mi0lic"); $result = json_decode($content); print_r( $result->data->children->data->title );... – Jennifer Nelen Apr 02 '21 at 16:27

1 Answers1

0

The issue can be found here:

print_r( $result->data->children->data->title ); ...

$result->data->children is an Array holding all the comments returned by the API.

We should 'search' all those comments (in your example, it's just 1) for the desired object.

Consider the following code example we're I've used array_filter to custom filter the objects found in $result->data->children array.

<?php

// Search string
$search = 'Gonna make this my new alarm ringtone';

// Get json using CURL
$json = getJson('t3_mi0lic');

// Search ->children
$res = array_filter($json->data->children, function ($child) use ($search) {

    // Include if ->data->title qeuals search
    return $child->data->title === $search;
});

// Show result
var_dump($res);




// Get JSON by $userId
function getJson($userId) {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.reddit.com/api/info/?id=' . $userId,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    return json_decode($response);
}
0stone0
  • 34,288
  • 4
  • 39
  • 64