I am using Youtube data v3 api to check for livestreams on channels using the following code, and it is working perfect but the issue with the youtube api quota limitation it is very low and it blocks if I exceed the quota, is there a way to avoid this quota or use another way?
<?php
// Ensure no output or whitespace before this point
header('Content-Type: application/json');
$servername = "localhost";
$username = "root"; // Your MySQL username
$password = ""; // Your MySQL password
$dbname = "youtube_channels_db";
$apiKey = "api key"; // Replace with your YouTube Data API key
// Function to check if a channel is live
function isLive($channelId, $apiKey) {
$url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={$channelId}&type=video&eventType=live&key={$apiKey}";
$response = file_get_contents($url);
$data = json_decode($response, true);
return !empty($data['items']); // Returns true if there are live items
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch all channels
$sql = "SELECT name, url FROM channels";
$result = $conn->query($sql);
$channels = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Extract channel ID from URL
$channelId = null;
if (preg_match('/(?:https?://)?(?:www.)?youtube.com/(?:channel/|user/|c/)?([a-zA-Z0-9_-]+)/', $row['url'], $matches)) {
$channelId = $matches[1];
}
// If channel ID is found, check if the channel is live
if ($channelId) {
$row['isLive'] = isLive($channelId, $apiKey);
} else {
$row['isLive'] = false; // Default to not live if no channel ID is found
}
$channels[] = $row;
}
}
$conn->close();
// Return channels as JSON
echo json_encode($channels);
?>
1