youtube API有时会抛出错误:在非对象上调用成员函数children()

时间:2012-11-10 17:50:33

标签: youtube-api php

当我启动php脚本时,有时工作正常,但很多时候它会检索我这个错误

  

致命错误:在非对象中调用成员函数children()   /membri/americanhorizo​​n/ytvideo/rilevametadatadaurlyoutube.php在线   21

这是代码的第一部分

// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/dZec2Lbr_r8';

// read feed into SimpleXML object
$entry = simplexml_load_file($feedURL);

$video = parseVideoEntry($entry);


function parseVideoEntry($entry) {      
  $obj= new stdClass;

  // get nodes in media: namespace for media information
  $media = $entry->children('http://search.yahoo.com/mrss/'); //<----this is the doomed line 21 

更新:采用解决方案

   for ($i=0 ; $i< count($fileArray); $i++)
  {

    // set feed URL
    $feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$fileArray[$i];


    // read feed into SimpleXML object
    $entry = simplexml_load_file($feedURL);


   if (is_object($entry))
   {
       $video = parseVideoEntry($entry);

       echo ($video->description."|".$video->length);
       echo "<br>";
    }
     else
     {
       $i--;
     }

 }

在此模式下,我强制脚本重新检查导致错误的文件

2 个答案:

答案 0 :(得分:2)

您首先要调用一个函数:

$entry = simplexml_load_file($feedURL);

该函数具有返回值。您会在该功能的手册页上找到它:

然后以变量$entry的形式使用该返回值,而不验证函数调用是否成功。

因此,您接下来会遇到错误。但是你的错误/错误是你如何处理函数的返回值。

不正确处理返回值就像是在呼唤麻烦。阅读您使用的功能,检查返回值并根据成功或错误条件继续。

$entry = simplexml_load_file($feedURL);

if (FALSE === $entry)
{
    // youtube not available.
}
else 
{
    // that's what I love!
}

答案 1 :(得分:-3)

有时?真? 看看这个:

<?php

$dummy; //IN FACT, this var is NULL now

// Will throw exactly the same error you get
$dummy->children();

为什么呢?因为,我们可以从对象类型调用方法。

所以,如果你想避免像这样的错误,下次你会调用这个方法,确保它“可能”。

<?php

if ( is_object($dummy) && method_exists($dummy, 'children') ){
   //sure it works
   $dummy->children();
}