-
Notifications
You must be signed in to change notification settings - Fork 27
/
PhpTube.php
113 lines (92 loc) · 3.09 KB
/
PhpTube.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/*
* @package PhpTube - A PHP class to get youtube download links
* @author Abu Ashraf Masnun <[email protected]>
* @website http://masnun.com
*
*/
class PhpTube
{
/**
* Parses the youtube URL and returns error message or array of download links
*
* @param $watchUrl the URL of the Youtube video
* @return string|array the error message or the array of download links
*/
public function getDownloadLink($watchUrl)
{
//utf8 encode and convert "&"
$html = utf8_encode($this->_getHtml($watchUrl));
$html = str_replace("\u0026amp;", "&", $html);
//get format url
preg_match_all('/url_encoded_fmt_stream_map\=(.*)/', $html, $matches);
$formatUrl = urldecode($matches[1][0]);
//split the format url into individual urls
$urls = preg_split('/url=/', $formatUrl);
$videoUrls = array();
foreach ($urls as $url)
{
/*
* Process the url and cut off the unnecessary data
*/
$url = urldecode($url);
$urlparts = explode(";", $url);
$url = $urlparts[0];
$urlparts = explode(",", $url);
$url = $urlparts[0];
/*
* Process type
*/
parse_str($url, $data);
if (isset($data['watermark']) || empty($url))
{
continue;
}
else
{
if (!empty($data['type']) && !empty($data['quality']))
{
$videoUrls[] = array("type" => $data['type'], "quality" => $data['quality'], "url" => $url);
}
}
}
return $videoUrls;
}
/**
* Parses the YouTube URL's and return them back to the developer
*
* @param $watchUrls the URLs of the Youtube video's
* @return array|array the error message or the array of download links
*/
public function getDownloadLinks(array $watchUrls = array())
{
// Loops throught the url and return a array which contains all of the converted links
$converted = array();
foreach ($watchUrls as $watchUrl)
{
$converted[] = $this->getDownloadLink($watchUrl);
}
return $converted;
}
/**
* A wrapper around the cURL library to fetch the content of the url
*
* @throws Exception if the curl extension is not available (or loaded)
* @param $url the url of the page to fetch the content of
* @return string the content of the url
*/
private function _getHtml($url)
{
if (function_exists("curl_init"))
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($ch);
}
else
{
throw new Exception("No cURL module available");
}
}
}