我正在构建一个带有搜索功能的网页,您可以在其中搜索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播放。
答案 0 :(得分: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>'; ?>