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 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页