Beaucoup de monde se pose la question comment télécharger les vidéos youtube via PHP sur son serveur, voilà une classe php qui permet de télécharger les vidéo youtube.
Dépendances
- Zend_Json
- Zend_Http_Client
Exemple
<?php require_once 'Youtube.php'; $youtube = new Youtube('http://www.youtube.com/watch?v=232AQHdnhTE'); $youtube->setFormat(Youtube::FORMAT_480P); $info = $youtube->download('./path/the/video/', 'movie_name');
Code
<?php /** * @author Axel ETCHEVERRY * @link http://www.axel-etcheverry.com * @copyright Copyright (c) 2010, Axel ETCHEVERRY (http://www.axel-etcheverry.com). * Displays <a href="http://opensource.org/licenses/gpl-license.php">GNU Public License</a> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @version Youtube 1.0 */ /** * @see Zend_Json */ require_once 'Zend/Json.php'; /** * @see Zend_Http_Client */ require_once 'Zend/Http/Client.php'; class Youtube { const FORMAT_360P = 6; const FORMAT_480P = 18; const FORMAT_720P = 22; const FORMAT_1080P = 37; /** * Youtube id * * @var string * @access protected */ protected $_id; /** * Youtube provider * @var string * @access protected */ protected $_provider = 'http://www.youtube.com/get_video'; /** * Vidéo format * * @var integer * @access protected */ protected $_format; /** * * @param string $url */ public function __construct($url) { $this->_id = self::getId($url); } /** * get yotube id * * @param string $url * @return String * @access public * @static */ public static function getId($url) { $url = parse_url($url, PHP_URL_QUERY); parse_str($url, $query); return $query['v']; } /** * set the vidéo format * * @param integer $format * @return Youtube * @access public */ public function setFormat($format) { $this->_format = (int)$format; return $this; } /** * Download video * * @param string $path * @param string $name * @return array * @access public */ public function download($path = './', $name = '') { $content = file_get_contents('http://www.youtube.com/watch?v=' . $this->_id); preg_match("/'SWF_ARGS': (.*),/", $content, $matches); unset($content); $json = Zend_Json::decode($matches[1]); unset($matches); $client = new Zend_Http_Client(); $client->setUri($this->_provider . '?video_id=' . $this->_id . '&t=' . urldecode($json['t']) . '&fmt=' . $this->_format); unset($json); $client->setConfig(array( 'maxredirects' => 0, 'timeout' => 30 )); $response = $client->request(); unset($client); $headers = $response->getHeaders(); unset($response); if(empty($name)) { $name = $this->_id; } $filename = $path . $name . '.mp4'; file_put_contents($filename, file_get_contents($headers['Location'])); unset($headers); $info = Zend_Json::decode(file_get_contents('http://www.youtube.com/oembed?url=http%3A//www.youtube.com/watch?v%3D' . $this->_id . '&format=json')); return array( 'id' => $this->_id, 'format' => $this->_format, 'title' => $info['title'], 'file' => $filename ); } }
























