2013-04-18 68 views
0

我有以下代碼:獲取YouTube數據API的縮略圖用SimpleXML

$rss = simplexml_load_file('http://gdata.youtube.com/feeds/api/playlists/PLEA1736AA2720470C?v=2&prettyprint=true'); 

foreach ($rss->entry as $entry) { 
    // get nodes in media: namespace for media information 
    $media = $entry->children('http://search.yahoo.com/mrss/'); 
    $thumbs = $media->group->thumbnail; 
    $thumb_attrs = array(); 
    $index = 0; 
    // get thumbnails attributes: url | height | width 
    foreach ($thumbs as $thumb) { 
     foreach ($thumb->attributes() as $attr => $value) { 
      $thumb_attrs[$index][$attr] = $value; 
      print $attr . ': ' . $thumb_attrs[$index][$attr] . "| "; 
     } 
     $index++; 
     print "<br>"; 
    } 
} 

則打印輸出:

url: http://i.ytimg.com/vi/te28_L-dO88/default.jpg| height: 90| width: 120| time: 00:00:49| 
... 

從以下格式的XML標籤:

<media:thumbnail url='http://i.ytimg.com/vi/4l4rwvAPhfA/default.jpg' height='90' width='120' time='00:02:23.500' yt:name='default'/> 
... 

如何添加名稱空間yt name ='default'的屬性,我沒有進入數組?

我怎樣才能得到最接近的所有寬度值與數組中的其他值?類似於PHP - Nearest value from an array,但考慮到我的數組是多維的。

回答

0

Simplexml和命名空間的問題是,您必須通過名稱來訪問任何名稱空間元素或屬性 - 也就是說,不能說「給我所有屬性而不管命名空間」。所以,你必須做一些循環,依靠的SimpleXML的命名空間的工具:

$rss = simplexml_load_file('http://gdata.youtube.com/feeds/api/playlists/PLEA1736AA2720470C?v=2&prettyprint=true'); 
$namespaces=$rss->getNameSpaces(true); // access all the namespaces used in the tree 
array_unshift($namespaces,""); // add a blank at the beginning of the array to deal with the unprefixed default 
foreach ($rss->entry as $entry) { 
    // get nodes in media: namespace for media information 
    $media = $entry->children('http://search.yahoo.com/mrss/'); 
    $thumbs = $media->group->thumbnail; 
    $thumb_attrs = array(); 
    $index = 0; 
    // get thumbnails attributes: url | height | width 
    foreach ($thumbs as $thumb) { 
     $attrstring=""; 
     foreach ($namespaces as $ns) { 
       foreach ($thumb->attributes($ns) as $attr => $value) { // get all attributes, whatever namespace they might be in 
         $thumb_attrs[$index][$attr] = $value; 
         $attrstring.=$attr . ': ' . $thumb_attrs[$index][$attr] . "| "; 
       } 
     } 
     print $attrstring; 
     $index++; 
     print "<br>"; 
    } 
} 

至於你的問題的第二部分,我不是100%肯定你問什麼。如果它真的和你鏈接的問題類似,那麼你是不是可以在循環之前創建一個空數組,並將每個條目的寬度添加到該數組中?當你的循環完成後,你將得到一個只有寬度的扁平數組。

但是,如果你問別的東西,也許你可以澄清?