这是我的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']);
}
答案 0 :(得分:0)
不,没有更好的解析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
找到它