2011-11-23 58 views
3

我的YouTube內部框架/像這樣對象的數組:PHP從iframe/object嵌入數組中提取youtube視頻ID?

[0] => <iframe width="600" height="338" src="http://www.youtube.com/embed/szL_PVuzWp0?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe> 
[1] => <object width="600" height="338"><param name="movie" value="http://www.youtube.com/v/jm1S43a-e3Y?version=3&feature=oembed"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/jm1S43a-e3Y?version=3&feature=oembed" type="application/x-shockwave-flash" width="600" height="338" allowscriptaccess="always" allowfullscreen="true"></embed></object> 
[2] => <iframe width="600" height="338" src="http://www.youtube.com/embed/7fTploFSbXA?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe> 
[3] => <iframe width="600" height="338" src="http://www.youtube.com/embed/vQSRNYgiuMk?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe> 

注意,嵌入方法可以變化(通常,偶爾<object>)(由於外部數據源)。

對於每個人我將如何/最可靠的方法去提取視頻URL(例如vQSRNYgiuMk或jm1S43a-e3Y)?

最後,我想用這樣一個數組,結束了:

[0] => "szL_PVuzWp0" 
[1] => "jm1S43a-e3Y" 
[2] => "7fTploFSbXA" 
[3] => "vQSRNYgiuMk" 
+0

的可能重複(http://stackoverflow.com/questions/1773822/get-youtube-video-id-from [從PHP的HTML代碼查看YouTube影片ID] -html-code-with-php) –

回答

0
foreach($arr as $i=>$a){ 
    $start = strpos($a, "/v/") + 3; 
    if(!$start) $start = strpos($a, "/embed/") + 7; 
    $qm = strpos("?"); 
    $length = $qm - $start; 
    $new_array[$i] = substr($a, $start, $length); 
} 
+0

關閉,但會導致例如'/ v/jm1S43a-'或'/ embed/szL_'(包括11個字符中的前綴) – sgb

+0

也可以,IIRC youtube網址可以是10-12個字符長。 – sgb

+0

這是一個體面的解決方案,所以謝謝這個問題。 但更廣泛的上下文中更好的解決方案是直接訪問URL(在外部API中添加一個參數),而不是在HTML中。 – sgb

5

不要使用正則表達式請:

$dom_document = new DOMDocument(); 

    $dom_document->loadHTML($html); 

    //use DOMXpath to navigate the html with the DOM 
    $dom_xpath = new DOMXpath($dom_document); 

    // if you want to get the all the iframes 
    $iframes = $dom_xpath->query("//iframe"); 

    if (!is_null($iframes)) { 
     foreach ($iframes as $iframe) { 
     if($iframe->hasAttributes()){ 
      $attributes = $iframe->attributes; 
      if(!is_null($attributes)){ 
       foreach ($attributes as $index=>$attr){ 
        if($attr->name == 'src'){ 
        $curSrc = $attr->value; 
        //use regex here to extract what you want 
        } 
       } 
      } 
     } 
     } 
    } 

一個完整的解決方案。但你明白了吧...

+0

是否有必要使用DOM?這是訪問src字符串的最簡單方法嗎? – sgb

+0

@samb您正在嘗試使用正則表達式解析html。雖然可以完成,但最終結果將不是一個很好的解析器。用DOM你不會出錯。如果你的html結構發生了變化,如果你使用了一個簡單的正則表達式,你註定會失敗。 – FailedDev

+0

感謝您的信息。 – sgb