Get info from API/URL - php

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.

Related

How to display this JSON data 'item' only once in this foreach loop (PHP)

I have a small function that grabs the avatars of comment authors on a specified video. It simply loops through the JSON data returned by YouTube API v3 commentThreads method.
The only issue is that sometimes an author has commented more than once, so my function is displaying the authors avatar more than once. I'd like to only display it one time, and on to the next avatar.
Here's a picture of what I mean:
Currently my function looks like this:
function videoCommentAvatars($video) {
// Parse YouTube video ID from the url
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $video, $match)) {
$video_id = $match[1];
}
// Gather Video stats with YouTube API v3
$api_key = "API_KEY_HERE";
$JSON = file_get_contents('https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId='.$video_id.'&key='.$api_key);
$json_data = json_decode($JSON, true);
if (!empty($json_data)) {
foreach ($json_data['items'] as $data) {
// Create variables that hold info
$author_name = $data['snippet']['topLevelComment']['snippet']['authorDisplayName']; // Author Name
$author_avatar = $data['snippet']['topLevelComment']['snippet']['authorProfileImageUrl']; // Author Avatar
$author_channel = $data['snippet']['topLevelComment']['snippet']['authorChannelUrl']; // Author Channel URL
echo '<span class="comment-author-avatar">';
echo '<a target="_blank" href="'.$author_channel.'" title="'.$author_name.'"><img width="50" alt="'.$author_name.'" class="comment-author-thumb-single" src="'.$author_avatar.'"></a>';
echo '</span>';
}
}
}
Everything works fine, but there's no way to check if an avatar has been displayed yet. I thought about using an array maybe? Adding each avatar URL to the array, and checking the array to see if the key exists. But that seems like overkill for something that's seemingly more simple. Does anyone have a clever way of checking the foreach loop for duplicates?
to check for duplicates in an array, you have a few options. Firstly, to get rid of any before looping, you can use array_unqiue($array) which will return an array that does not repeat it's values.
Or if you do need initial access to all values in the loop, and to do something if a repeat is present, you can have another array that acts as a record to see if they appear more than once.
$record = array();
foreach ($json_data['items'] as $data) {
// Create variables that hold info
$author_name = $data['snippet']['topLevelComment']['snippet']['authorDisplayName']; // Author Name
if(!in_array($author_name, $record)){
$author_avatar = $data['snippet']['topLevelComment']['snippet']['authorProfileImageUrl']; // Author Avatar
$author_channel = $data['snippet']['topLevelComment']['snippet']['authorChannelUrl']; // Author Channel URL
echo '<span class="comment-author-avatar">';
echo '<a target="_blank" href="'.$author_channel.'" title="'.$author_name.'"><img width="50" alt="'.$author_name.'" class="comment-author-thumb-single" src="'.$author_avatar.'"></a>';
echo '</span>';
$record[] = $author_name;
}
}
You can try a multi array with a unique index in your loop.
$author[$data['snippet'][...]['authorDisplayName']['avatar'] = $data['snippet'][...]['authorProfileImageUrl'];
So only unique results in the array.

Get a JSON from url with 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.

parsing SEO friendly url without htaccess or mode_rewrite

Can anyone suggest a method in php or a function for parsingSEO friendly urls that doesn't involve htaccess or mod_rewrite? Examples would be awesome.
http://url.org/file.php/test/test2#3
This returns: Array ( scheme] => http [host] => url.org [path] => /file.php/test/test2 [fragment] => 3 ) /file.php/test/test2
How would I separate out the /file.php/test/test2 section? I guess test and test2 would be arguments.
EDIT:
#Martijn - I did figure out what your suggested before getting the notification about your answer. Thanks btw. Is this considered an ok method?
$url = 'http://url.org/file.php/arg1/arg2#3';
$test = parse_url($url);
echo "host: $test[host] <br>";
echo "path: $test[path] <br>";
echo "frag: $test[fragment] <br>";
$path = explode("/", trim($test[path]));
echo "1: $path[1] <br>";
echo "2: $path[2] <br>";
echo "3: $path[3] <br>";
echo "4: $path[4] <br>";
You can use explode to get the parts from your array:
$path = trim($array['path'], "/"); // trim the path of slashes
$path = explode("/", $path);
unset($path[0]); // the first one is the file, the others are sections of the url
If you really want to make it zerobased again, add this as last line:
$patch = array_values($path);
In response to your edit:
You want to make this as flexible as you can, so no fixed coding based on a max of 5 items. Although you probably will never exceed that, just don't pin yourself to it, just overhead you dont need.
If you have a pages system like this:
id parent name url
1 -1 Foo foo
2 1 Bar, child of Foo bar-child-of-foo
Make a recursive function. Pass the array to a function which takes the first section to find a root item
SELECT * FROM pages WHERE parent=-1 AND url=$path[0]
That query will return an id, use that in the parent column with the next value of the array. Unset each found value of the $path array. In the end, you will have an array with the remaining parts.
To sketch an example:
function GetFullPath(&$path, $parent=-1){
$path = "/"; // start with a slash
// Make the query for childs of this item
$result = mysqli_query($conn, "SELECT * FROM pages WHERE parent=".$parent." AND url=".current($path)." LIMIT 1");
// If any rows exists, append more of the url via recursiveness:
if($result->num_rows!==0){
// Remove the first part so if we go one deeper we start with the next value
$path = array_slice($patch,1); // remove first value
$fetch = $result->fetch_assoc();
// Use the fetched value to go deeper, find a child with the current item as parent
$path.= GetFullPath($path, $fetch['parent']);
}
// Return the result. if nothing is found at all, the result will be "/", probs home
return $path;
}
echo GetFullPath($path); // I pass it by reference, any alterations in the function happen to the variable outside the scope aswell
This is a draft, I did not test this, but you get the idea im trying to sketch. You can use the same method to get the ID of the page you are at. Just keep passing the variable back up again c
One of these days im getting the hang of recursiveness ^^.
Edit again: Oops, that turned out to be quite some code.

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

store an array value to a new variable using it's key - twitter api

I'm trying to write code that will return the past 100 tweets that contain the current trending hashtags on twitter. First I get the contents of the current trends and isolate just trending hashtags:
$json_output=json_decode(file_get_contents("https://api.twitter.com/1/trends/23424977.json"),true);
print_r($json_output);
foreach($json_output[0]['trends'] as $trend) {
if ($trend['name'][0] === '#') {
echo $trend['name'];
$hashtag == $trend['name'];
}
}
But rather than echo the trend['name'], I want to use it to search using the twitter search method. By adding something like this inside the if statement:
$past_uses = json_decode(file_get_contents("http://search.twitter.com/search.json?q="$hashtag"&rpp=100&include_entities=true&result_type=popular"),true);
But the variable $hashtag isn't being defined properly and I don't know why. (When I try to echo $hashtags, to check that it's storing the proper value, it doesn't print anything.) So, what should I change so that the value of $trend['name'] can be used in the URL for the search method in order to get the past tweets that included the trending hashtag?
Thank you!
You're doing a comparison instead of assigning $hashtag.
$hashtag == $trend['name'];
That's basically just saying false inline. Instead, use a single equal sign:
$hashtag = $trend['name'];
Also, for your $past_uses, make sure you concatenate the string with dots properly:
$past_uses = json_decode(
file_get_contents("http://search.twitter.com/search.json?q=" . $hashtag . "&rpp=100&include_entities=true&result_type=popular"),
true);

Categories