I am trying to use the YouTube v3 API to show all the videos from a particular YouTube playlist. Here is my code so far:
<?php
$playlistId = 'PLHGPqm6HHcedxhoMXo9m9yKqsOmOB_S0F';
$maxResults = 20;
$apiKey = 'APIKEYHERE';
$string = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId='.$playlistId.'&maxResults='.$maxResults.'&key='.$apiKey.''));
foreach($string['items'] as $item) {
echo $item['title'];
}
?>
I have used Postman to test the url and it is definitely getting data but when i try to echo any data it isn't showing.
I have learnt that Json decode will return stdclass by default json_decode php.net so you would have to replace foreach with this:
foreach($string->items as $item) {
echo $item->snippet->title;
}
Related
I want to get artist name from last.fm api
HEre is a code
$jsonData = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&limit=56&api_key=MYAPIKEY&format=json');
$jsonData = json_decode($jsonData, true);
foreach ($jsonData['tracks']['track'] as $track) {
$title = $track['name'];
$image = $track['image'][3]['#text'];
echo '<div id="track_short"><div class="track_short">
<a href="http://'.$SiteUrl.'/mp3-download-'.cano($title).'/" ><img src="'.$image.'" alt="'.$title.'">
<div class="description"><p class="description_content">'.$title.'</p>
</div></a></div></div>';
}
Example of API data
{"tracks":{"track":[{"name":"Sorry","duration":"0","playcount":"1931615","listeners":"193074","mbid":"","url":"http://www.last.fm/music/Justin+Bieber/_/Sorry","streamable":{"#text":"0","fulltrack":"0"},"artist":{"name":"Justin Bieber","mbid":"e0140a67-e4d1-4f13-8a01-364355bee46e","url":"http://www.last.fm/music/Justin+Bieber"},"image":[{"#text":"http://img2-ak.lst.fm/i/u/34s/d5af34cbc048b190fc7369acdcf8655b.png","size":"small"},{"#text":"http://img2-ak.lst.fm/i/u/64s/d5af34cbc048b190fc7369acdcf8655b.png","size":"medium"},{"#text":"http://img2-ak.lst.fm/i/u/174s/d5af34cbc048b190fc7369acdcf8655b.png","size":"large"},{"#text":"http://img2-ak.lst.fm/i/u/300x300/d5af34cbc048b190fc7369acdcf8655b.png","size":"extralarge"}]}],"#attr":{"page":"1","perPage":"1","totalPages":"253572626","total":"253572626"}}}
cool thanks i have correct
from : $phpArtist = $phpJson['tracks']['track'][0]['artist'];
to : $Artist = $track['artist']['name'];
and its working, thanks
Using PHP's json_decode() method:
$json = '{"tracks":{"track":[{"name":"Sorry","duration":"0","playcount":"1931615","listeners":"193074","mbid":"","url":"http://www.last.fm/music/Justin+Bieber/_/Sorry","streamable":{"#text":"0","fulltrack":"0"},"artist":{"name":"Justin Bieber","mbid":"e0140a67-e4d1-4f13-8a01-364355bee46e","url":"http://www.last.fm/music/Justin+Bieber"},"image":[{"#text":"http://img2-ak.lst.fm/i/u/34s/d5af34cbc048b190fc7369acdcf8655b.png","size":"small"},{"#text":"http://img2-ak.lst.fm/i/u/64s/d5af34cbc048b190fc7369acdcf8655b.png","size":"medium"},{"#text":"http://img2-ak.lst.fm/i/u/174s/d5af34cbc048b190fc7369acdcf8655b.png","size":"large"},{"#text":"http://img2-ak.lst.fm/i/u/300x300/d5af34cbc048b190fc7369acdcf8655b.png","size":"extralarge"}]}],"#attr":{"page":"1","perPage":"1","totalPages":"253572626","total":"253572626"}}}';
$phpJson = json_decode($json, true, 10); //4 is the depth of the JSON string, but you can make this a big number and it will still work
$phpArtist = $phpJson['tracks']['track'][0]['artist']['name'];
Let me know if that works, or if the php needs to get tweaked, I don't have a PHP client up right now.
I'm trying to parse JSON sent by POST to my webservice.
I'm using Advanced Rest Client tool for Google Chrome to test restapi.
How can I read this request and response to it?
I'm sending key called "format" and "json" as value for this key. I'm adding JSON like
"{"id":"235325"}"
Part of my PHP API code:
if( strcasecmp($format,'json') == 0 )
{
//how to read that id = 235325?
}
Try the json_decode() function. It is the standard function to parse json in php.
If want to work with array:
$json = '{"id":"235325"}';
$array = json_decode($json, true);
foreach($array as $element){
if($element == 0){
}
}
With object:
$json = '{"id":"235325"}';
$object = json_decode($json);
if($object->id == 0){
}
Here is my PHP/JSON code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$decoded= json_decode($json);
$data=$decoded->matches[0];
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
Now I have the following problem
Notice: Trying to get property of non-object
and
Notice: Undefined property: stdClass::$team1
I just want use foreach loop and then show my results in HTML.
Why I am getting the 2 mentioned problems and how can I show the correct results?
Ok so the url your are using return VALID JSON, no need to change any of it!
I suggest using arrays, it has always appeared simpler to me
Do you want the logo_url from team or image_url from league? I will show both in my implementation.
So here is some corrected code
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
//I am not sure which one you want!!!
echo $value['league']['image_url'] . "<br>";
echo $value['team1']['logo_url'] . "<br>";
echo $value['team2']['logo_url'] . "<br>";
}
*EDIT To show wanted implementation by questions author...
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
echo "
<img src=\"http://dailydota2.com/{$value['team1']['logo_url']}\">
<img src=\"http://dailydota2.com/{$value['team2']['logo_url']}\">
";
}
I have checked your code and have some notes and hopefully a solution:
1- You are trying to get non existing key from JSON data, that is the message telling you.
2- I am still not sure what do you get from the JSON API. But regarding to dailydota2 documentation there is nothing called image_url under team1. I guess you are looking for logo_url or something like that.
3- Do not change the format of JSON as you do in your code, therefore delete following line:
$json=str_replace('}, ]',"} ]",$json);
Just leave the main JSON output from API as default.
4- When you try to get specific key from the decoded JSON/Array just use following way:
$data = $decoded->{'matches'};
in stead of
$data=$decoded->matches[0];
Reference: http://php.net/manual/en/function.json-decode.php
5- And finally your foreach loop is working but needs the correct key:
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
When all these step is done, it should works.
Here is your final corrected code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded = json_decode($json);
$data = $decoded->{'matches'};
foreach ($data as $value) {
print_r($value->team1->logo_url);
echo '<img src="http://dailydota2.com/' . $value->team1->logo_url . '">';
}
It returns following output, and I do not get any errors.
/images/logos/teams/cdecgaming.png/images/logos/teams/teamempire.png
/images/logos/teams/ehome.png/images/logos/teams/ehome.png
/images/logos/teams/fnatic.png/images/logos/teams/cloud9.png
/images/logos/teams/teamissecret.png/images/logos/teams/teamissecret.png
/images/logos/teams/natusvincere.png/images/logos/teams/fnatic.png
Again I really do not know which information you want to get from the API but here you have a base of working code that you can work further with to get the required data from the right KEYs.
$youtube = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2');
$title = $youtube->title;
This gets the title. But how could I get the viewcount and description? tried $youtube->description; and $youtube->views;
I suggest you to use the JSON output instead of the XML one.
You can get it by adding the alt=json parameter to your URL:
http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json
Then you have to load the json and parse it:
<?php
$json_output = file_get_contents("http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json");
$json = json_decode($json_output, true);
//This gives you the video description
$video_description = $json['entry']['media$group']['media$description']['$t'];
//This gives you the video views count
$view_count = $json['entry']['yt$statistics']['viewCount'];
//This gives you the video title
$video_title = $json['entry']['title']['$t'];
?>
Hope this helps.
UPDATE
To see what variables does the JSON output have, add the prettyprint=true parameter to the URL and open it in your browser, it will beautify the JSON output to make it more comprehensible:
http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json&prettyprint=true
Instead of browsing the URL you can just write
echo "<pre>";
print_r($json);
echo "</pre>";
after
$json = json_decode($json_output, true);
and it will print the formatted JSON output
My code:
$vId = "Jer8XjMrUB4";
$gkey = "AIzaSyCO5lIc_Jlrey0aroqf1cHXVF1MUXLNuR0";
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=".$vId."&key=".$gkey."");
$data = json_decode($dur, true);
foreach ($data['items'] as $rowdata) {
$vTime = $rowdata['contentDetails']['duration'];
$desc = $rowdata['snippet']['description'];
}
$interval = new DateInterval($vTime);
$vsec = $interval->h * 3600 + $interval->i * 60 + $interval->s;
if($vsec > 3600)
$vsec = gmdate("H:i:s", $vsec);
else
$vsec = gmdate("i:s", $vsec);
echo $vsec."--".$desc;
Result:
02:47--Following the critically acclaimed global smash hit X-Men:
Youtube API V2.0 has been deprecated.You must have to switch to V3 API.Which need API key.
So prefer to use but In this way so can not get video description
http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=ktt3C7nQbbA&format=json
I am trying to get discriptiobn from youtube using api .... but i dont no where am i wrong its not getting for single video . but if i try playlist its working fine, not with video id
Here is my code
error_reporting(E_ALL);
$feedURL = 'https://gdata.youtube.com/feeds/api/playlists/'.$id.'?v=2&prettyprint=true';
$sxml = simplexml_load_file($feedURL);
echo $feedURL.'</br>';
foreach ($sxml->entry as $entry)
{
echo $media->group->description;
}
Above code is working with playlist ... but if i try one video its not working:
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$id.'?v=2&alt=json&prettyprint=true';
$sxml = simplexml_load_file($feedURL);
echo $feedURL.'</br>';
foreach ($sxml->entry as $entry)
{
echo $media->group->description;
}
If you call YouTube api with 'alt=json' parameter, the response will be formatted as JSON not XML. So you should use:
$response = json_decode(file_get_contents('... API URL ...'), true);
And then 'description' can be accessed with:
$response['entry']['media$group']['media$description']['$t']