Php - 在表格中显示youtube视频

时间:2016-01-29 14:20:22

标签: php xml youtube

我正在使用youtube v3 api。经过几次测试后,我意识到我需要一些帮助。当我试图显示xml内容时,我只是获取空值。有人能帮助我吗?

如果你想看xml:

  

https://www.youtube.com/feeds/videos.xml?channel_id= $的channelID

我的代码是:

$xml=simplexml_load_file("videos.xml");
foreach($xml as $content) { 
     echo $content->title . "<br>"; 
     echo $content->link['href'] . "<br>"; 

}

我要显示的Xml:

<entry>
Video ID <yt:videoId>Q4vSZA_8kYY</yt:videoId>
Video title <title>¡Trailer del canal! CBPrductions</title>

Upload date <published>2016-01-14T07:37:03+00:00</published>

<media:group>
Description <media:description>
LIKE PORQUE LO DIGO YO _ Suscribete!: https://www.youtube.com/user/SpanishCBProductions Dale a LIKE a mi página Facebook: https://www.facebook.com/SpanishCBProductions Sigueme en TWITTER!: https://twitter.com/CcristianN3 Y en mi poco sexy INSTAGRAM: http://instagram.com/ccristiann3/
</media:description>
</media:group>
</entry>

1 个答案:

答案 0 :(得分:2)

我认为您可以注册命名空间并使用xpath。 然后对于'media'和'yt',您可以通过传递命名空间来获取children

如果要显示第一个条目:

$url = 'https://www.youtube.com/feeds/videos.xml?channel_id=UCRGn72Qu0KTtI_ujNxRr3Fg';
$xml = simplexml_load_file($url);
$ns = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$elements = $xml->xpath('//a:entry');
$content = $elements[0];

$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " .$media->group->description . "<br>";

如果要显示所有条目的信息,可以使用:

foreach ($elements as $content) {
    $yt = $content->children('http://www.youtube.com/xml/schemas/2015');
    $media = $content->children('http://search.yahoo.com/mrss/');
    echo "Video ID: " . $yt->videoId . "<br>";
    echo "Video title: " . $content->title . "<br>";
    echo "Upload date: " . $content->published . "<br>";
    echo "Description: " . $media->group->description . "<br>";
    echo "<br>";
}