Mostrando o potencial da JS Calls PHP #3 – acessando a API do Youtube

Segue abaixo mais um exemplo do que pode ser feito com a JS Calls PHP: acessar a API do Youtube.

Veja aqui uma página de exemplo!

Como? Primeiro, baixei essa classe que está no repositório do PHPClasses, que faz todo o trabalho de requisitar a API e trabalhar com o retorno, num xml. Só alterer a mesma criando o método searchStreamingLinks(), o qual exponho para a biblioteca.

<?php
define(“ANY”,0);
define(“PC”,1);
define(“MOBILE”,2);

/**
* This class fetching live streaming links of youtube videos, both for mobile (real player) and PC (flash player)
*
*@author Rochak Chauhan [www.dmwtechnologies.com]
*/
class YoutubeAPI {
private $startIndex=1;
private $format=PC;
private $maxResults=10;
private $keyword=””;
private $feedString=””;
private $downloadUrl=”http://demo.dmwtechnologies.com/YouTubeDownloader/index.php”;

public function __construct() {

}

/**
* Function to get the XML code from the YouTubeAPI
*
* @param string $url
* @access private
*
* @return string
*/
private function getXmlCodeViaFopen($url){
$returnStr=””;
$fp=fopen($url, “r”) or die(“ERROR: Illigal YouTube API URL”);
while (!feof($fp)) {
$returnStr.=fgetc($fp);
}
fclose($fp);
return $returnStr;
}

/**
* Function to get the Title from the XML/RSS Feed
*
* @param string $str
* @access private
* @return string
*/
private function getTitle($str) {
$final=array();
$returnArray=array();
$pattern=”/<title type=’text’>(.*)\<\/title\>/Uis”;
preg_match_all($pattern, $str, $returnArray, PREG_SET_ORDER);
if(isset($returnArray[0][1])) {
return $returnArray[0][1];
}
else {
return “NA”;
}
}

/**
* Function to get the FLV/SWF url from the XML/RSS Feed
*
* @param string $str
* @access private
* @return string
*/
private function getFlvUrl($str) {
$final=array();
$returnArray=array();
$pattern=”/<media:player url=’(.*)’/Uis”;
//$pattern=”/<media:content url=’(.*)’ type=’application\/x-shockwave-flash’/Uis”;
preg_match_all($pattern, $str, $returnArray, PREG_SET_ORDER);

if(isset($returnArray[0][1])) {
return $returnArray[0][1];
}
else {
return “#”;
}
}

/**
* Function to get the mobile streaming url from the XML/RSS Feed
*
* @param string $str
* @access private
* @return string
*/
private function getMobileUrl($str) {

$final=array();
$returnArray=array();
$pattern=”/<media:content url=’(.*)’ type=’video\/3gpp’/Uis”;
preg_match_all($pattern, $str, $returnArray, PREG_SET_ORDER);

if(isset($returnArray[1][1])) {
return $returnArray[1][1];
}
else {
return “#”;
}
}

/**
* Function to get the video thumbnail from the XML/RSS Feed
*
* @param string $str
* @access private
* @param boolean $returnAllThumbsAsArray
* @return string
*/
private function getThumbnailUrl($str,$returnAllThumbsAsArray=false) {
$final=array();
$returnArray=array();
$imgArray=array();
$imgPattern=”/<media:thumbnail url=’(.*)’/Uis”;
preg_match_all($imgPattern, $str, $tmp, PREG_SET_ORDER);

$c=count($tmp);
$l=-1;
foreach($tmp as $key=>$value){
$value=$value[1];
$imgArray[]=$value;
}
if($returnAllThumbsAsArray===true){
return $imgArray;
}
else{
return $imgArray[3];
}
}

/**
* Function to get Streaming link info
*
* @param string $feed
* @access public
* @return array
*/
public function getStreamingLinks() {
$feed=$this->feedString;
$final=array();
$returnArray=array();
$pattern=”/<title type=’text’>(.*)<category scheme=’http:\/\/gdata.youtube.com\/schemas\/2007\/keywords.cat’/Uis”;
preg_match_all($pattern, $feed, $returnArray, PREG_SET_ORDER);

for($i=1;$i<count($returnArray);$i++){
$str=$returnArray[$i][0];
$title=$this->getTitle($str);
$flvUrl=$this->getFlvUrl($str);
$mobileUrl=$this->getMobileUrl($str);
$thumbnailUrl=$this->getThumbnailUrl($str);
if ($this->format==PC) {
$final[]=array(“title”=>$title,”flvurl”=>$flvUrl,”thumbnailUrl”=>$thumbnailUrl);
}
elseif ($this->format==MOBILE) {
$final[]=array(“title”=>$title,”mobileurl”=>$mobileUrl,”thumbnailUrl”=>$thumbnailUrl);
}
else {
$final[]=array(“title”=>$title,”flvurl”=>$flvUrl,”mobileurl”=>$mobileUrl,”thumbnailUrl”=>$thumbnailUrl);
}
}
return $final;
}

/**
* Function to get the downloadable link of the flv file
*
* @param string $youtubeUrl
* @return array on success else false
* @access public
*/
public function getDownloadLink($youtubeUrl) {
// get download link Page
$post_data=”url=$youtubeUrl”;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->downloadUrl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$htmlCode = curl_exec($ch);
curl_close($ch);
$returnArray=array();
// extract link from the htmlcode
$pattern=”/<a href=’(.*)\<\/a\>/Uis”;
preg_match_all($pattern, $htmlCode, $returnArray, PREG_SET_ORDER);
if(isset($returnArray[0][1])) {
$str=trim($returnArray[0][1]);
$pos=strpos($str,”‘”);
$link=substr($str,0,$pos);
$title=strip_tags($returnArray[0][0]);
return array(“title”=>$title,”link”=>$link);
}
else {
return false;
}
}

public function searchStreamingLinks($keyword,$maxResults=10,$startIndex=1) {
$this->keyword=$keyword;
$this->format=ANY;
$this->maxResults=$maxResults;
$this->startIndex=$startIndex;
$url=”http://gdata.youtube.com/feeds/api/videos?vq=” . urlencode($keyword) .”&start-index=$startIndex&max-results=$maxResults”;
$this->feedString=$this->getXmlCodeViaFopen($url);
return $this->getStreamingLinks();
}

}
?>

No config.php da JS Calls PHP expus a classe sob o nome youtube e, com isso, posso acessar o método searchStreamingLinks passando uma palavra-chave como parâmetro e, ainda, quantos items quero exibir e qual o primeiro item a ser exibido.

<html>
<head>
<script type=”text/javascript” src=”../engine.js”></script>
<script type=”text/javascript” src=”../interface/youtube.js”></script>
<script type=”text/javascript”>

function getVideos() {
document.getElementById(“videos”).innerHTML = “aguarde, buscando…”;
youtube.searchStreamingLinks(document.getElementById(“keyword”).value, 10, 1, function(videos) {
var ul = document.createElement(“ul”);
for(var i=0; i<videos.length; i++) {
var video = videos[i];

var a = document.createElement(“a”);
a.innerHTML = video.title;
a.href = video.flvurl;

var img = document.createElement(“img”);
img.src = video.thumbnailUrl;

var li = document.createElement(“li”);
li.appendChild(img);
li.appendChild(a);

ul.appendChild(li);
}
document.getElementById(“videos”).innerHTML = “”;
document.getElementById(“videos”).appendChild(ul);
});

}

</script>
</head>
<body>
<h1>JS Calls PHP</h1>
<h2>Exemplo de uso – acesso a API do Youtube</h2>
<label for=”keyword”>Palavra-chave:</label><input type=”text” name=”keyword” id=”keyword” />
<a href=”#” onClick=”getVideos(); return false;”>buscar</a><br /><br />
<div id=”videos”></div>
</body>
</html>

No retorno da chamada tenho uma lista de objetos, e cada objeto possui atributos title, flvurl e thumbnailUrl – com os quais posso montar a lista de vídeos!

Faça download da JS Calls PHP aqui

Posts relacionados

2 thoughts on “Mostrando o potencial da JS Calls PHP #3 – acessando a API do Youtube

Deixe uma resposta

O seu endereço de email não será publicado Campos obrigatórios são marcados *

Você pode usar estas tags e atributos de HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>