PHP extract youtube video IDs from array of iframe/object embeds?

梦想的初衷 提交于 2019-12-23 17:18:47

问题


I have an array of youtube iframes/objects like so:

[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>

Note that the embed method can vary (usually <iframe>, occasionally <object>) (due to external data source).

How would I/what is the most reliable method to go about extracting the video URL (e.g. vQSRNYgiuMk or jm1S43a-e3Y) for each one?

Ultimately I want to end up with an array like so:

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

回答1:


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);
}



回答2:


Don't use regex please :

   $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
                  } 
               } 
            } 
         } 
      }
   }

Not a complete solution. But you get the point...



来源:https://stackoverflow.com/questions/8244508/php-extract-youtube-video-ids-from-array-of-iframe-object-embeds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!