开发者

PHP YouTube API Video Title Parsing

I'm using some regexes to parse wiki-styled text.

<?php
function wikiParser($da开发者_Go百科ta){
 $data = preg_replace('/\[\[Youtube:([a-zA-Z0-9_]+)\]\]/', getYoutubeTitle("$1"), $data);
 return $data;
}
?>

This function searches for strings like [[Youtube:b32hRITAAew]] and calles another function getYoutubeTitle(b32hRITAAew).

<?php
function getYoutubeTitle($hash){
 $url = 'http://gdata.youtube.com/feeds/api/videos?v=2&q='.$hash.'&max-results=1&fields=entry(title)&prettyprint=true';
 $fp = fopen($url, 'r');
 $page = '';
 while(!feof($fp)){
  $page .= fgets($fp, 4096);
 }
 $titre = eregi("<title>(.*)</title>", $page, $regs);
 return $regs[1]; 
}
?>

The second function parses the response data. In the case of b32hRITAAew code, the following url is accessed

http://gdata.youtube.com/feeds/api/videos?v=2&q=b32hRITAAew&max-results=1&fields=entry(title)&prettyprint=true

It outputs:

<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'>
    <entry>
        <title>The Lord of the Rings Symphony (1) HQ</title>
    </entry>
</feed>

And the title should be The Lord of the Rings Symphony (1) HQ. But for the unknown reason it shows me some random Photography Trick - Easy Image Stabilizer For Any Camera. I've worked hard to solve the issue, but still can't get it how that comes up. Is there any problem with getYoutubeTitle("$1") or anything else?


You can use the preg_replace_callback function like this:

function wikiParser($data){
 $data = preg_replace_callback('/\[\[Youtube:([a-zA-Z0-9_]+)\]\]/', "getYoutubeTitle", $data);
 return $data;
}

function getYoutubeTitle($array){
 // $array looks like this: Array ( [0] => [[Youtube:b32hRITAAew]] [1] => b32hRITAAew )
 $hash = array_pop($array);
 $url = 'http://gdata.youtube.com/feeds/api/videos?v=2&q='.$hash.'&max-results=1&fields=entry(title)&prettyprint=true';
 ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜