2012-02-16 134 views
1

使用Youtube頻道如何解析$ link變量並獲取視頻ID?我能得到的鏈接,但parse_str部分似乎並不正常工作YouTube從鏈接解析視頻ID

YouTube的ID解析:試圖讓下面

if (! empty($xml->channel->item[0]->link)) 
{ 
    parse_str(parse_url($xml->channel->item[0]->link, PHP_URL_QUERY), $url_query); 

    if (! empty($url_query['v'])) 
    $id = $url_query['v']; 
} 

echo $id; 

當前的代碼以目前的代碼工作:

<?php 
    $id = NULL; 
    $username = 'utahblaze'; 
    $url = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?orderby=updated&max-results=8'; 
    $xml = simplexml_load_file(sprintf($url, $username)); 

    foreach ($xml->entry as $entry) : 

     $kids = $entry->children('http://search.yahoo.com/mrss/'); 
     $attributes = $kids->group->content[0]->attributes(); 
     $flv = $attributes['url']; 
     $attributes = $kids->group->player->attributes(); 
     $link = $attributes['url']; 


    echo $id; 
    echo $link; 

    ?> 

<a id="ytopen" href="<?=$link?>"> 
<img src="http://i4.ytimg.com/vi/<?=$id?>/default.jpg" /></a> 

    <?php endforeach; ?> 
+1

+1不使用正則表達式來解析PHP中的URL。 – 2012-02-16 20:28:19

回答

2

把這個後$link = $attributes['url'];

$querystring = parse_url($link); 
$id = $querystring['query']; 
$path = $querystring['path']; 
$host = $querystring['host']; 
$scheme = $querystring['scheme']; 

parse_str($querystring['query'], $id_temp); 

$link = $scheme . '://' . $host . $path . '/' . $id_temp['v']; 
+0

非常感謝,工作得很好。我如何在每個鏈接的末尾解析出'&feature = youtube_gdata_player' ... http://www.youtube.com/watch?v=hU-bUIAygSY&feature=youtube_gdata_player – acctman 2012-02-17 17:02:18

+0

用代碼編輯我的答案,解析出&&功能'。等待同行評審以顯示 – seanbreeden 2012-02-17 18:12:21

+1

@seanbreeden您試圖編輯OP - 嘗試在您的答案下的編輯鏈接。您應該始終能夠立即編輯自己的答案。對OP的編輯已被拒絕。 – Basic 2012-02-17 18:49:04