Search code examples
phpyoutube-apiyoutube-data-apiyoutube-livestreaming-api

LiveChatMessages API YouTube returns null


I am trying to get messages from the live chat chat using a GET request.

$json_result = file_get_contents("https://www.googleapis.com/youtube/v3/liveChat/messages?liveChatId=$videoId&part=snippet&key=$api_key");
// $videoId и $api_key true, there are no errors.
echo '<pre>';
var_dump(json_decode($json_result));
echo '</pre>';

In the answer I get NULL, tell me what is the error or what method can I get messages from the YouTube broadcast chat?


Solution

  • Maybe it will be useful for someone, solved the issue through cURL instead of file_get_contents.

    $curl_handle=curl_init();
    curl_setopt($curl_handle, CURLOPT_URL,"https://www.googleapis.com/youtube/v3/liveChat/messages?liveChatId=$LiveChatId&part=snippet%2CauthorDetails&maxResults=200&key=$api_key");
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_USERAGENT, 'JeezLand API');
    $json_results = curl_exec($curl_handle);
    curl_close($curl_handle);
    $json_decode_results = json_decode($json_results);
    foreach($json_decode_results as $json_decode_result){
        foreach($json_decode_result as $result){
            /* echo '<pre>';
                var_dump($result);
            echo '</pre>'; */
            echo $result->authorDetails->displayName.' -> '.$result->snippet->displayMessage.'<br />';
        }
    }
    

    Special thanks to Gert de Pagter for the help on solving the problem.