2012-12-04 27 views
0

我正在建立一个网页,其搜索功能可以搜索YouTube视频,点击搜索后,这些视频将显示在同一页面上。现在我想让它们可以播放,所以当用户搜索歌曲时,它会将用户重定向到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

视频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>'; ?> 
+0

它不工作它给我的错误。 –