【问题标题】:PHP YouTube API Video Title ParsingPHP YouTube API 视频标题解析
【发布时间】:2011-08-25 03:14:55
【问题描述】:

我正在使用一些正则表达式来解析 wiki 样式的文本。

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

此函数搜索 [[Youtube:b32hRITAAew]] 之类的字符串并调用另一个函数 getYoutubeTitle(b32hRITAAew) em>。

<?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]; 
}
?>

第二个函数解析响应数据。 b32hRITAAew代码的情况下,访问如下url

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

它输出:

<?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>

标题应该是指环王交响曲(1)总部。但由于未知原因,它向我展示了一些随机的摄影技巧 - 适用于任何相机的简易图像稳定器。我一直在努力解决这个问题,但仍然无法理解它是如何出现的。 getYoutubeTitle("$1") 或其他有什么问题吗?

【问题讨论】:

    标签: php regex api youtube youtube-api


    【解决方案1】:

    您可以像这样使用 preg_replace_callback 函数:

    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';
     ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 2015-10-23
      • 2012-03-28
      • 2017-10-14
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 2016-02-25
      • 2015-11-19
      相关资源
      最近更新 更多