【发布时间】: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']);
}
【问题讨论】: