使用SimpleXML获取缩略图的Youtube数据API


Get Youtube data API for thumbnails with 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 -最接近数组的值,但考虑到我的数组是多维的。

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

关于你问题的第二部分,我不是百分之百确定你在问什么。如果它确实与您链接到的问题相似,您是否可以在循环之前创建一个空数组,并将每个条目的宽度添加到该数组中?当你的循环完成后,你就会得到一个宽度刚好的扁平数组。

但如果你问别的问题,也许你可以澄清一下?