0

我正在构建一个具有搜索功能的网页,您可以在其中搜索 youtube 视频,点击搜索后,这些视频将显示在同一页面上。现在我想让它们也可以播放,所以当用户搜索歌曲时,它会将用户重定向到 youtube,但它会在同一页面播放视频。

这是我搜索 youtube 视频的代码:

?php      
// if form submitted
} else {
  // check for search keywords
  // trim whitespace
  // separate multiple keywords with /

  if (!isset($_POST['q']) || empty($_POST['q'])) {
    die ('ERROR: Please enter one or more search keywords');
  } 
  else {
    $q = $_POST['q'];
    //$q = preg_replace('[[:space:]]', '/', trim($q));

  }
  // set max results
  if (!isset($_POST['i']) || empty($_POST['i'])) {
    $i = 25;
  } else {
    $i = $_POST['i'];
  }

  // generate feed URL
  $feedURL = "http://gdata.youtube.com/feeds/api/videos/-/{$q}?orderby=viewCount&max-results={$i}";
  //$feedURL = "http://gdata.youtube.com/feeds/api/videos/-/eminem?orderby=viewCount&max-results=10";
  // read feed into SimpleXML object



  $sxml = simplexml_load_file($feedURL);
  //var_dump($sxml);

  // get summary counts from opensearch: namespace
  $counts = $sxml-> children('http://a9.com/-/spec/opensearchrss/1.0/');
  //$counts = $sxml-> children('http://www.opensearch.org/Specifications/OpenSearch/1.1');

  $total = $counts->totalResults;
  $startOffset = $counts->startIndex; 
  $endOffset = ($startOffset-1) + $counts->itemsPerPage;       
  ?>

  <h1>Search results</h1>
  <?php echo $total; ?> items found. Showing items 
  <?php echo $startOffset; ?> to <?php echo $endOffset; ?>:
  <p/>

  <table>
  <?php    
  // iterate over entries in resultset
  // print each entry's details
  foreach ($sxml->entry as $entry) {
    // get nodes in media: namespace for media information
    $media = $entry->children('http://search.yahoo.com/mrss/');

    // get video player URL
    $attrs = $media->group->player->attributes();
    $watch = $attrs['url']; 

    // get video thumbnail
    $attrs = $media->group->thumbnail[0]->attributes();
    $thumbnail = $attrs['url']; 

    // get <yt:duration> node for video length
    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->duration->attributes();
    $length = $attrs['seconds']; 

    // get <gd:rating> node for video ratings
    $gd = $entry->children('http://schemas.google.com/g/2005'); 
    if ($gd->rating) {
      $attrs = $gd->rating->attributes();
      $rating = $attrs['average']; 
    } else {
      $rating = 0; 
    }

    // to get the video player
    $url = $watch;
    parse_str( parse_url( $url, PHP_URL_QUERY ), $video_id );

  }
}
?>

我的问题是如何使用 youtube Iframe 播放我页面上的所有视频,而不是去 youtube 播放它。

4

1 回答 1

0

视频 ID 在该 XML 文件内的多个不同位置可用。您可以加载 XML 的这一部分:

...<entry><id>http://gdata.youtube.com/feeds/api/videos/uelHwf8o7_U</id>...

对其运行正则表达式以提取视频 ID,然后将该 ID 插入此代码中:

<?php $ajax_return = '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.$youtube_ID.'" frameborder="0" allowfullscreen></iframe>'; ?>
于 2012-12-04T14:29:28.747 回答