Get YouTube video title in PHP

后端 未结 7 1686
陌清茗
陌清茗 2021-01-22 22:44

In one of my applications I am saving a YouTube video\'s id... Like "A4fR3sDprOE". I have to display its title in the application. I got the following code for getting

7条回答
  •  孤城傲影
    2021-01-22 23:03

    It's not safe to use file_get_contents() with remote URLs. Use cURL instead with YouTube API 2.0:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds/api/videos/' . $video_id);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $xml   = new SimpleXMLElement($response);
        $title = (string) $xml->title;
    } else {
        // Error handling.
    }
    

提交回复
热议问题