Get a JSON from url with PHP - php

Im new to php and tried to get a json object from the twitch API to retrieve one of its values and output it. i.e
i need to get the information from this link: https://api.twitch.tv/kraken/users/USERNAME/follows/channels/CHANNELSNAME
plus i need to to something so i can modify the urls USERNAME and CHANNELSUSERNAME. I want it to be a api to call for howlong user XY is following channelXY and this will be called using nightbots $customapi function.
the date i need from the json is "created_at"
Since we were able to clear out the errorsheres the final PHP file that works if anyone encounters similiar errors:
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
?>

You have a typo in your code on the first line and you're not storing the result of your json_decode anywhere.
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
You have to call the page this way page.php?username=yeroise&channel=ceratia in order to output the created_at value for this user and this channel.
In your code you're using 2 different ways to get the content of the page and you only need one (either file_get_contents or using CURL), I chose file_get_contents here as the other method adds complexity for no reason in this case.

Related

Get info from API/URL

I have the URL https://android.rediptv2.com/ch.php?usercode=5266113827&pid=1&mac=02:00:00:00:00:00&sn=&customer=GOOGLE&lang=eng&cs=amlogic&check=3177926680
which outputs statistics.
For example:
[{"id":"2972","name":"MBC 1","link":"http://46.105.112.116/?watch=TR/mbc1-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC1En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc1.png"},{"id":"1858","name":"MBC 2","link":"http://46.105.112.116/?watch=TN/mbc2-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC2En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc2.png"},{"id":"1859","name":"MBC 3","link":"http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc3.png"}]
I want to get the value of link count.
Can anyone help?
I tried to do:
<?php
$content = file_get_contents("https://android.rediptv2.com/ch.php?usercode=5266113827&pid=1&mac=02:00:00:00:00:00&sn=&customer=GOOGLE&lang=eng&cs=amlogic&check=3177926680");
$result = json_decode($content);
print_r( $result->link );
?>
But it didn't work.
Put the JSON in an editor and you'll see that it's an array and not an object with the link attribute. This is why you cannot access it directly. You have to loop over the items and then you'll be able to access the link property of one of the items. If you need to access the link by id, as you asked 4 months later, then just create a dictionnary in an array indexed by id and containing just the interesting data you need.
PHP code:
<?php
// The result of the request:
$content = <<<END_OF_STRING
[{"id":"2972","name":"MBC 1","link":"http://46.105.112.116/?watch=TR/mbc1-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC1En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc1.png"},{"id":"1858","name":"MBC 2","link":"http://46.105.112.116/?watch=TN/mbc2-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC2En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc2.png"},{"id":"1859","name":"MBC 3","link":"http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc3.png"}]
END_OF_STRING;
$items = json_decode($content);
echo '$items = ' . var_export($items, true) . "\n\n";
// Create a dictionnary to store each link accessible by id.
$links_by_id = [];
// Loop over all items:
foreach ($items as $i => $item) {
// Show how to access the current link.
echo "Link $i = $item->link\n";
// Fill the dictionary.
$links_by_id[(int)$item->id] = $item->link;
}
// To access the first one:
echo "\nFirst link = " . $items[0]->link . "\n";
// Example of access by id:
// The id seems to be a string. It could probably be "1895" or "zhb34" or whatever.
// (If they are only numbers, we could convert the string to an integer).
$id = "1859";
echo "\nAccess with id $id = " . $links_by_id[$id] . "\n";
Test it here: https://onlinephp.io/c/e8ab9
Another important point: You are getting a 403 Forbidden error on the URL you provided. So typically, you will not obtain the JSON you wanted.
As I explained in the comment below, I think that you will not be able to access this page without having a fresh URL with valid query parameters and/or cookies. I imagine you obtained this URL from somewhere and it is no longer valid. This is why you'll probably need to use cURL to visit the website with a session to obtain the fresh URL to the JSON API. Use Google to find some examples of PHP scraping/crawling with session handling. You'll see that depending on the website it can get rather tricky, especially if some JavaScript comes into the game.

PHP function to call JSON files

I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};

Httpful JSON inside an array

I've been trying for 3 days to get PHP to show the ID from this test JSON using PHP and httpful.
Anyone have any ideas as i've tried loads of different combinations and even tried created a handler to decode as an array... I just suck at PHP ?
// Make a request to the GitHub API with a custom
// header of "X-Trvial-Header: Just as a demo".
<?php
include('\httpful.phar');
$url = "https://jsonplaceholder.typicode.com/posts";
$response = Httpful\Request::get($url)
->expectsJson()
->send();
echo "{$response[0]['id']}";
?>
My output... still nothing
You are not properly indexing the return value.
The response is a mixed value. So you should do something like below to get what you are looking for.
<?php
include('\httpful.phar');
$url = "https://jsonplaceholder.typicode.com/posts";
$response = Httpful\Request::get($url)
->expectsJson()
->send();
echo $response->body[0]->id;
?>

Parsing Instagram json data to usable variable in php

I have a working api call to get basic user info and I am trying to return just the "followed_by" portion of the json data from "counts".
This link should return just the json page on your browser
https://api.instagram.com/v1/users/self/?access_token=3514554632.a691e29.3f773f5f335a4ba98fc9609d1d405fb0
And here is my code to try and parse the result, but all I am getting is a blank screen.
$jsondata = file_get_contents("https://api.instagram.com/v1/users/self/?access_token=3514554632.a691e29.3f773f5f335a4ba98fc9609d1d405fb0");
$json = json_decode($jsondata, true);
$json2 = json_decode($jsondata);
//method one to parse, not working
$parsedvalue = $json['counts'][1]['followed_by'];
echo $parsedvalue;
//method two to parse, not working
$followercount = $json2->counts->followed_by;
echo $followercount;
Here is the fix I got figured out for //method 2
$jsondata = file_get_contents("https://api.instagram.com/v1/users/self/?access_token=3514554632.a691e29.3f773f5f335a4ba98fc9609d1d405fb0");
$json2 = json_decode($jsondata);
$followercount = $json2->data->counts->followed_by;
This properly returns your follower count, but I still need help understanding how to fix method one

How to run a search for any movie using the Rotten Tomatoes API?

Could anyone help me to create search for movies using PHP when connecting to the Rotten Tomatoes API?
On the Rotten Tomatoes site they give you example code how to get content for specific movie like so:
<?php
$apikey = 'insert_your_api_key_here';
$q = urlencode('Toy Story'); // make sure to url encode an query parameters
// construct the query with our apikey and the query we want to make
$endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=' . $apikey . '&q=' . $q;
// setup curl to make a call to the endpoint
$session = curl_init($endpoint);
// indicates that we want the response back
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// exec curl and get the data back
$data = curl_exec($session);
// remember to close the curl session once we are finished retrieveing the data
curl_close($session);
// decode the json data to make it easier to parse the php
$search_results = json_decode($data);
if ($search_results === NULL) die('Error parsing json');
// play with the data!
$movies = $search_results->movies;
echo '<ul>';
foreach ($movies as $movie) {
echo '<li>' . $movie->title . " (" . $movie->year . ")</li>";
}
echo '</ul>';
?>
I'm an beginner with PHP so an example would be great. I have manage to solve this with JavaScript but the server I have to host the page won't display it because of updates. So now I will have to turn to PHP because it displays the code from above too.
You need to create a form with a text field. Name the field q so it will work with your sample code.
Have the form post to the url of your sample php script.
Remove this line:
$q = urlencode('Toy Story');
Replace it with this:
$q = urlencode($_POST['q']);
That should get you started.
Note that no effort is made to sanitize the $_GET. I am just providing the basics you need to have a search form running based on the example code you posted.
If you do not know how to create a form, here is a link to a tutorial:
http://www.tizag.com/phpT/forms.php

Categories