可捕获的致命错误:类DOMNodeList的对象无法转换为字符串

时间:2014-04-28 20:14:36

标签: php

我正在使用我的PHP来获取网址列表。我使用domdocument来获取输入的url列表,我想将请求发送到每个url以获取返回字符串。

当我尝试这个时:

  if($link->getAttribute('href'))
  {
     if(!$link->hasAttribute('id') || $link->getAttribute('id')!='streams')
     {
       $url = str_replace("rtmp://", "", $link->getAttribute('href'));
       $url = str_replace(" ", "%20", $link->getAttribute('href'));
       echo $url;
       echo "<br>";
       $sdoc = new DOMDocument();
       $sdoc->strictErrorChecking = false;
       $sdoc->recover=true;
       @$sdoc->loadHTMLFile($url);
       $spans = $sdoc->getElementsByTagName('span');
       echo $spans;
     }
  }

我会得到这个:可捕获的致命错误:类DOMNodeList的对象无法转换为字符串。

错误是跳到这一行:

echo $spans;

以下是我要解析的每个网址的时间字符串列表:

<span id="time1">4:00 PM</span> - 
<span id="time2">4:30 PM</span> 
<span id="time3">5:00 PM</span> 
<span id="time4">5:30 PM</span>
<span id="time5">6:00 PM</span>

以下是代码:

<?php
ini_set('max_execution_time', 300);
$errmsg_arr = array();
$errflag = false;

$xml .= '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '
<tv generator-info-name="www.mysite.com/xmltv">';

$baseUrl = file_get_contents('http://http://www.mysite.com/get-listing.php');

$domdoc = new DOMDocument();
$domdoc->strictErrorChecking = false;
$domdoc->recover=true;
//@$domdoc->loadHTMLFile($baseUrl);
@$domdoc->loadHTML($baseUrl);

//$links = $domdoc->getElementsByTagName('test');
//$links = $domdoc->getElementById('test');
$links = $domdoc->getElementsByTagName('a');

$data = array();
foreach($links as $link)
{
  //echo $link->getAttribute('id, test');
  //echo $test;


  //echo $domdoc->saveXML($link);
  if($link->getAttribute('href'))
  {
     if(!$link->hasAttribute('id') || $link->getAttribute('id')!='streams')
     {
       $url = str_replace("rtmp://", "", $link->getAttribute('href'));
       $url = str_replace(" ", "%20", $link->getAttribute('href'));
       echo $url;
       echo "<br>";
       $sdoc = new DOMDocument();
       $sdoc->strictErrorChecking = false;
       $sdoc->recover=true;
       @$sdoc->loadHTMLFile($url);
       $spans = $sdoc->getElementsByTagName('span');
       $query = parse_url($url)['query'];
       $url_split = explode("&", $query)[0];
       $channel = urldecode(explode("=",$url_split)[1]);

       foreach($spans as $span)
       {
         $id = $span->getAttribute('time1');
         //echo $id;
       }
     }
  }
}
?>

你能否告诉我为什么我会得到可卡死的致命错误以及我如何回应时间字符串?

2 个答案:

答案 0 :(得分:1)

您尝试接收的值并不明显,但如果是时间,您可以使用node->nodeValue

foreach($spans as $span)
   {
     echo $span->nodeValue;     
   }

答案 1 :(得分:1)

因为您正在获取列表,并且需要遍历它。试试这个:

for ($i = 0; $i < $spans->length; $i++) {
   echo $spans->item($i)->nodeValue . "\n";
}

并查看这是否有助于您获得所需内容。

您也可以使用foreach:

foreach ($spans as $time) {
    echo $time->nodeValue . "\n";
}

参考:http://www.php.net/manual/en/domnodelist.item.php