douzi9430 2011-05-13 17:30
浏览 42
已采纳

PHP YouTube API视频标题解析

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

<?php
function wikiParser($data){
 $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?

  • 写回答

1条回答 默认 最新

  • doudan5136 2011-05-13 17:48
    关注

    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';
     ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接