2011-11-23 128 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