Jump to content

How To Get Multple Users Youtube Videos


Lone_Ranger
Go to solution Solved by QuickOldCar,

Recommended Posts

I have attached the file

 

http://www.sentuamessage.com/index.php?action=communitytube is the example of what is happening

 

Hi,

 

I have a table in my database that has a bunch of usernames stored in a column, I am using that column to retrieve the usernames and access there youtube account to retrieve the most recent 13 videos.

 

Any blank left cell should not show anything.

 

Right now the code is retrieving the users videos but is duplicating them. One users videos would show 26 times.

 

The other problem I have is that I do not want to show 13 videos for each user. I wanted to access all the recent videos from every user who input there username in the youtube field but only show 13 recent videos in total from all the users.

 

I have attached the file can anyone help me please?

ztest.php

Link to comment
Share on other sites

$communityvideos = mysql_query("SELECT * FROM userdb WHERE rights='user' && youtube<>''"); while($youtube = mysql_fetch_assoc($communityvideos)) {

I have updated the SQL query to the above, this was done to get rid of some of the duplicate problem where users who contained a blank field under youtube would be showing up in my result.

Link to comment
Share on other sites

Do you order by a date or an id?

 

You were looping multiple times and also returning 13 from each users feed

array_count_values() is what is needed here

<?php
//Adding limit to the end would get you a limited amount of results
$communityvideos = mysql_query("SELECT * FROM userdb WHERE rights='user' && youtube<>'' LIMIT 13");

//end your while loop and create the $v array

$v = array(); //define array
while ($youtube = mysql_fetch_assoc($communityvideos)) {
    $v[] = trim($youtube['youtube']); //is this the user?
}

//check that v array is not empty
if (!empty($v)) {
    //here we get each users count for videos
    $user_count = array_count_values($v);
   
    //Now loop through the 13 results from $user_count array which has usernames and amounts of videos each
    foreach ($user_count as $user => $video_amount) {
        //echo "$user has $video_amount <br />";
       
        $feedURL = 'http://gdata.youtube.com/feeds/api/users/' . $user . '/uploads?max-results=' . $video_amount;
        $sxml    = simplexml_load_file($feedURL);
       
        foreach ($sxml->entry as $entry) {
            $media     = $entry->children('media', true);
            $watch     = (string) $media->group->player->attributes()->url;
            $thumbnail = (string) $media->group->thumbnail[0]->attributes()->url;
           
            parse_str(parse_url($watch, PHP_URL_QUERY), $my_array_of_vars);
           
           
            //you can add the rest
        }
       
       
    } //end $user_count loop
} //end if $v
?>

Link to comment
Share on other sites

If my logic of getting all the latest video and a user can have more than one video does not work.....Was not sure if you were marking who just added one somehow or if there is never supposed to be a duplicate user.

If the latter is the case you should be inserting these using a unique index on the youtube

ALTER TABLE `userdb`
ADD UNIQUE INDEX `user_index` (`youtube`);

Use DISTINCT in the mysql query and loop each unique user with 1 max_result from youtube api

$communityvideos = mysql_query("SELECT DISTINCT youtube  FROM userdb WHERE rights='user' && youtube<>'' LIMIT 13");

while ($youtube = mysql_fetch_assoc($communityvideos)) {
    $user = trim($youtube['youtube']);

$feedURL = 'http://gdata.youtube.com/feeds/api/users/' . $user . '/uploads?max-results=1';

//and so on

}
Link to comment
Share on other sites

Sorry, you werent very clear on your answer.

First of get the total videos uploaded by calling the api with a json format:
   http://gdata.youtube.com/feeds/api/users/LinusTechTips/uploads?v=2&alt=jsonc

use:
   $json = json_decode($jsonString); 
   print($json->data->totalItems . "\n");

to get the viewcount, then you can calculate the rest!
   $totalItems = $json->data->totalItems;
   $maxResults = 50
   $xmlResults = array();
   for($i = $maxResults > $totalItems-50; $i+$maxResults) {
          $xmlResults[] = simplexml_load_file(
             'http://gdata.youtube.com/feeds/api/users/LinusTechTips/uploads?max-results=' . $i
          );
   }

To be clear; this is not tested. So im not sure it works; but this is the way to do it. 

sorry I did find an answer for this but I do not understand the first part, apparently this is the best way to do it.

 

My problem is where he put the username "LINUSTECHLIPS" that is where I need to have my . $USER . as a loop, as the $USER would be going through the list of youtube usernames I have and want to get videos from.

 

Youtube API tends to put videos in most recent uploaded anyway, so from those usernames in my database all I want is 13 videos in total from all the users. That's why I had a $maxresults = 13 except for on my version it did 13 videos from each user not just 13 in total.

Link to comment
Share on other sites

error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/playlists/[theusername]?max-results=13';
$sxml = simplexml_load_file($feedURL);
$i=0;
foreach ($sxml->entry as $entry) {
      $media = $entry->children('media', true);
      $watch = (string)$media->group->player->attributes()->url;
      $thumbnail = (string)$media->group->thumbnail[0]->attributes()->url;

parse_str( parse_url( $watch, PHP_URL_QUERY ), $my_array_of_vars );

//any silky smooth layout someone wanted to add would go in this gap

$i++; if($i==5) { 

$i=0; 
 } 
  }

forget the new response then sorry. It was something someone said would work and I could not understand it how it would help me.

 

The original code as seen above was designed just to access the youtube API and retrieve the latest videos for 1 user. This would show those videos for that one user.

 

I was using this concept. The difference I did was create a column in USERDB where a user could type there youtube username into it so we could retrieve there vidoes. This cell was called YOUTUBE.

 

Then I wanted to create a dedicated page where using this concept of retrieving videos off the username, I could have a solo page which would only contain 13 videos in total from all those usernames I had stored in my database off the YOUTUBE column.

 

My database does not contain any links to the videos, does not contain anything else except for the YOUTUBE username.

Edited by Lone_Ranger
Link to comment
Share on other sites

What I gave should work for you.

 

You can try to prevent duplicate names being inserted into mysql in the first place by making the unique index.

 

or...

 

Use the code that has DISTINCT in the query if want just one video per user and only 13

 

I have done tons of youtube related scripts like video search engine including own api,scrapers/crawlers, ripping playlists,users,watch lists, custom playlist creation.

 

I'm beyond my limit as for sleep, try what you have here and would assist more after I sleep unless you get it or someone else helps.

Link to comment
Share on other sites

<?php
//Adding limit to the end would get you a limited amount of results
$communityvideos = mysql_query("SELECT * FROM userdb WHERE rights='user' && youtube<>'' LIMIT 13");

//end your while loop and create the $v array

$v = array(); //define array
while ($youtube = mysql_fetch_assoc($communityvideos)) {
    $v[] = trim($youtube['youtube']); //is this the user?


//check that v array is not empty
if (!empty($v)) {
    //here we get each users count for videos
    $user_count = array_count_values($v);
   
    //Now loop through the 13 results from $user_count array which has usernames and amounts of videos each
    foreach ($user_count as $user => $video_amount) {
        //echo "$user has $video_amount <br />";
}      
        $feedURL = 'http://gdata.youtube.com/feeds/api/users/' . $user . '/uploads?max-results=' . $video_amount;
        $sxml    = simplexml_load_file($feedURL);
       
        foreach ($sxml->entry as $entry) {
            $media     = $entry->children('media', true);
            $watch     = (string) $media->group->player->attributes()->url;
            $thumbnail = (string) $media->group->thumbnail[0]->attributes()->url;
           
            parse_str(parse_url($watch, PHP_URL_QUERY), $my_array_of_vars);
           
           
            //you can add the rest
        }
       
       
    } //end $user_count loop
} //end if $v
?>

I do apologise my good man your first answer worked marvellously I should have never doubted it and tried it first

Link to comment
Share on other sites

$feedURL = 'http://gdata.youtube.com/feeds/api/users/' . $user . '/uploads?orderby=published&max-results=' . $video_amount;

I changed the $feedurl to the above so the latest published video shows

 

but in my list now everything is in ID order, so USER 1 will be top going down to USER 13. I wanted the user with the latest PUBLISHED video to be top with the rest following so it always changes with a new content showing

Link to comment
Share on other sites

I wrote up something that can aggregate youtube videos by date with multiple users

<?php
date_default_timezone_set('America/Los_Angeles'); //set to your server timezone
//users array
$users  = array(
    "fffffffffffffffffffffffff",
    "KSIOlajidebt",
    "MissFushi",
    "UberHaxorNova"
);
$videos = array(); //define videos array

//function to fetch users videos
function fetchYT($user, $max = NULL)
{
    if ($max == NULL) {
        $max = 1;
    }
    $feedURL = "http://gdata.youtube.com/feeds/api/users/" . $user . "/uploads?v=2&max-results=" . $max . "&alt=jsonc";
    
    $json = @file_get_contents($feedURL);
    $json = json_decode($json, true);
    if (is_array($json)) {
        foreach ($json['data'] as $video) {
            if (is_array($video)) {
                return $video;
            }
        }
    }
}

//function to sort by date
function sortYTdate($a, $b)
{
    return strcmp($a['uploaded'], $b['uploaded']);
}

//loop users and fetch their videos
foreach ($users as $user) {
    $user_video_array = fetchYT($user, 2); //youtube username, max results per user
    if (!empty($user_video_array)) {
        //youtube upload date to strtotime
        foreach ($user_video_array as $video_array) {
            $date                    = substr($video_array['uploaded'], 0, strlen($video_array['uploaded']) - 1);
            $video_array['uploaded'] = strtotime($date);
            
            //create new videos array
            $videos[] = $video_array;
        }
        
        
    }
}

//function to aggregate returned videos by date
function aggregateYT($videos)
{
    if (is_array($videos) && !empty($videos)) {
        uasort($videos, 'sortYTdate');
        $videos = array_reverse($videos);
    }
    return $videos;
}

//display
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Aggregate Youtube Users Videos</title>
<style>
a{
text-decoration:none;    
}
img{
    padding:2px;
}
p{
    padding:2px;
}
</style>
</head>

<body>
<?php
if (!empty($videos)) {
    $videos = aggregateYT($videos);
    
    //show results of array
    echo '<pre>', print_r($videos, 1), '</pre>';
    
    foreach ($videos as $video) {
        echo "<a href='https://www.youtube.com/watch?v=" . $video['id'] . "' target='_blank'>" . $video['title'] . "</a><br />";
        echo "<a href='https://www.youtube.com/watch?v=" . $video['id'] . "' target='_blank'><img src='https://i.ytimg.com/vi/" . $video['id'] . "/default.jpg'/></a><br />";
        echo "<small>" . date("F j, Y, g:i:s a", $video['uploaded']) . "</small><br />";
        echo "<a href='https://www.youtube.com/user/" . $video['uploader'] . "' target='_blank'>" . $video['uploader'] . "</a><br />";
        echo $video['category'] . "<br />";
        echo "Duration: " . gmdate("H:i:s", $video['duration']) . "<br />";
        echo "<p>" . $video['description'] . "</p><br />";
    }
}
?>
</body>
</html>
Link to comment
Share on other sites

  • Solution

I made it into one function and easier to use

 

You just need to insert a users array

<?php
//config
date_default_timezone_set('America/Los_Angeles'); //set to your server timezone
//users array
$users = array(
    "fffffffffffffffffffffffff",
    "KSIOlajidebt",
    "MissFushi",
    "UberHaxorNova"
);



//function to fetch users videos
function fetchYT($user, $max = NULL)
{
    if ($max == NULL) {
        $max = 1;
    }
    $feedURL = "http://gdata.youtube.com/feeds/api/users/" . $user . "/uploads?v=2&max-results=" . $max . "&alt=jsonc";
    
    $json = @file_get_contents($feedURL);
    $json = json_decode($json, true);
    if (is_array($json)) {
        foreach ($json['data'] as $video) {
            if (is_array($video)) {
                return $video;
            }
        }
    }
}

//function to sort by date
function sortYTdate($a, $b)
{
    return strcmp($a['uploaded'], $b['uploaded']);
}


//function to aggregate returned videos by date
function aggregateYT($users)
{
    $videos = array(); //define videos array
    if (!is_array($users) || empty($users)) {
        return $videos['error'] = "no users array";
    }
    
    $videos = array(); //define videos array
    //loop users and fetch their videos
    foreach ($users as $user) {
        $user_video_array = fetchYT($user, 1); //youtube username, max results per user
        if (!empty($user_video_array)) {
            //youtube upload date to strtotime
            foreach ($user_video_array as $video_array) {
                $date                    = substr($video_array['uploaded'], 0, strlen($video_array['uploaded']) - 1);
                $video_array['uploaded'] = strtotime($date);
                
                //create new videos array
                $videos[] = $video_array;
            }
            
            
        }
    }
    
    
    if (!empty($videos)) {
        uasort($videos, 'sortYTdate');
        $videos = array_reverse($videos);
    } else {
        return $videos['error'] = "no videos found";
    }
    return $videos;
}

//display
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Aggregate Youtube Users Videos</title>
<style>
a{
text-decoration:none;    
}
img{
    padding:2px;
}
p{
    padding:2px;
}
</style>
</head>

<body>
<?php
if (empty($users)) {
    echo "No users found";
} else {
    //only function need to call on, have a users array
    $videos = aggregateYT($users);
    
    //show results of array
    //echo '<pre>', print_r($videos, 1), '</pre>';
    
    foreach ($videos as $video) {
        echo "<a href='https://www.youtube.com/watch?v=" . $video['id'] . "' target='_blank'>" . $video['title'] . "</a><br />";
        echo "<a href='https://www.youtube.com/watch?v=" . $video['id'] . "' target='_blank'><img src='https://i.ytimg.com/vi/" . $video['id'] . "/default.jpg'/></a><br />";
        echo "<small>" . date("F j, Y, g:i:s a", $video['uploaded']) . "</small><br />";
        echo "<a href='https://www.youtube.com/user/" . $video['uploader'] . "' target='_blank'>" . $video['uploader'] . "</a><br />";
        echo $video['category'] . "<br />";
        echo "Duration: " . gmdate("H:i:s", $video['duration']) . "<br />";
        echo "<p>" . $video['description'] . "</p><br />";
    }
}
?>
</body>
</html>
Edited by QuickOldCar
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.