【问题标题】:Is there a better way to parse Youtube API XML than this?还有比这更好的解析 Youtube API XML 的方法吗?
【发布时间】:2014-07-10 15:57:31
【问题描述】:

这是我的 PHP youtube 播放列表 API 程序的片段,以及我如何解析 XML 并将数据保存在 YoutubeVideo 对象中。有没有比这更好的解析 XML 的方法?请注意,这需要与 PHP 5+ 一起使用

-如果您想查看工作代码的演示,请访问@http://www.ericsicons.com/yt_playlistapi

-源代码为@https://github.com/ericsicons/PHP-Youtube-Playlist-API-Plug-in

$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/playlists/' . $playlistID
        . '?max-results=50&start-index=' . $startIndex);
if (!$xml) {
    throw new PlaylistNotFound(".: Error Opening Playlist " . $this->getID()
    . ", Please check if the playlist ID is valid :.");
}

$t = $xml->children('openSearch', true);

$this->playList['title'] = (string) $xml->title;
$this->playList['description'] = (string) $xml->subtitle;
$this->playList['numVideos'] = (string) $t->totalResults;

$i = -1;
foreach ($xml->entry as $entry) {
    $i++;
    // YT XML elements references
    $media = $entry->children('media', true);
    $yt = $entry->children('yt', true);
    $gd = $entry->children('gd', true);

    /* Creating the Video Objects */
    $this->videoList[] = new YouTubeVideo();
    $t = $media->group->player->attributes();
    parse_str(parse_url($t['url'], PHP_URL_QUERY), $vars);
    $this->videoList[$i]->setId($vars['v']);
    $t = $media->group->thumbnail[1]->attributes();
    $this->videoList[$i]->setThumbnail($t['url']);
    $this->videoList[$i]->setTitle($media->group->title);
    $this->videoList[$i]->setDescription($media->group->description);
    $t = $media->group->content->attributes();
    $this->videoList[$i]->setDuration($t['duration']);
    $this->videoList[$i]->setDatePublished($entry->published);
    $this->videoList[$i]->setAuthor($entry->author->name);
    $t = $yt->statistics->attributes();
    $this->videoList[$i]->setViews($t['viewCount']);
    $this->videoList[$i]->setFavorites($t['favoriteCount']);
    $t = $gd->rating->attributes();
    $this->videoList[$i]->setNumRaters($t['numRaters']);
} 

【问题讨论】:

    标签: php xml parsing youtube


    【解决方案1】:

    不,没有更好的解析 XML 的方法。不使用 SimpleXML 只会让事情变得更糟。

    这超出了问题的范围,但目前您正在使用 RSS+XML 输出 来自这个网址:https://gdata.youtube.com/feeds/api/users/migoicons/uploads

    虽然从 Youtube API 获取和解码 JSON 而不是 XML 可能更容易。 https://gdata.youtube.com/feeds/api/users/migoicons/uploads?v=2&alt=json

    <?php
    $json_playlist = file_get_contents('https://gdata.youtube.com/feeds/api/users/migoicons/uploads?v=2&alt=json');
    $playlist = json_decode($json_playlist);
    var_dump($playlist);
    

    请记住,Google 提供了一个不错的 PHP 客户端库来访问 Youtube API。 你可以在https://developers.google.com/youtube/v3/code_samples/php找到它

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2011-01-24
    相关资源
    最近更新 更多