Search code examples
phphttpsgetyoutube-apifile-get-contents

file_get_contents() "failed to open stream: Network is unreachable" error on valid link


There's an extremely simple example of using Youtube API in php that somehow fails to work in my case, and I couldn't find a definitive solution for.

I desire to use the Youtube API without any wrapper, by myself, to get data of videos. The following search:list query works perfectly when I try accessing it from within by browser (as a link), but in php, I get that error when I try the same.

        $apikey_YT = <my API key>;
        $ytrequrl = "https://www.googleapis.com/youtube/v3/search?".
                "part=snippet".
                "&maxResults=50".
                "&q=doom".
                "&relatedToVideoId=h8j2zj-A5tE".
                "&type=video".
                "&key=${apikey_YT}";

        $result = file_get_contents($ytrequrl);
        var_dump($result);

The potential issues were URL encoding, or allowing allow-url-fopen, but neither seemed to help in my case: the former actually gave a new error message: No such file or directory.

What can I do?


Solution

  • Try it like this. Might be your formatting. This works for me.

    $ytrequrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&q=doom&relatedToVideoId=h8j2zj-A5tE&type=video&key='.$apikey_YT;
    
    $info= file_get_contents($ytrequrl);
    $info= json_decode($info, true);
    
    print("<pre>".print_r($info,true)."</pre>");