Kaka Kaka - 5 months ago 14
PHP Question

Getting title, description and number of views of a youtube video

$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;

Answer

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