JamesG
JamesG

Reputation: 1601

PHP Invalid argument supplied for foreach() when getting RSS

I seem to be having trouble accessing a portion of an RSS feed. I have read this article: Accessing date as XML node in PHP and Problem getting author from a wordpress RSS feed using SimpleXmlElement article but I still cannot seem to get this to work.

<item>
  <title>This is the title</title>
  <dc:creator>!an (@myHandle)</dc:creator>
  <description><![CDATA[<p class="TweetTextSize  js-tweet-text tweet-text"  lang="en">What is this tweeet</p>]]></description>
  <pubDate>Tue, 03 Jan 2017 22:01:54 +0000</pubDate>
  <guid>1234567</guid>
  <link>1234567</link>
  <twitter:source/>
  <twitter:place/>
</item>

here is the portion of the rss I am getting. Here is the full RSS: https://twitrss.me/twitter_search_to_rss/?term=test+this+feed

I am trying to access this with PHP code like so:

$feed = new DOMDocument();
 $feed->load('https://twitrss.me/twitter_search_to_rss/?term=test+this+feed');

foreach ($feed->getElementsByTagName('channel')->item(0) as $item) {
  $ns_dc = $item->children('http://purl.org/dc/elements/1.1/');
  echo $ns_dc->creator;
}

but I keep getting this error:

Invalid argument supplied for foreach()

I have tried changing it to:

$feed->getElementsByTagName('channel')->item(0)

but then nothing outputs.

I also tried:

$feed->getElementsByTagName('channel')

but then get the error:

Call to undefined method DOMElement::children()

Question

Please can someone tell me, using PHP how to access the dc:creator tag and assign that value to a variable?

Edit

      $i = 1;
  foreach ($feed->channel as $row) {
    echo $i;
    
      foreach ($row->children() as $key => $val) {
          if ($key == "item") {
            if ($i == 1) {
              $ns_dc = $val->children('http://purl.org/dc/elements/1.1/');
              echo $ns_dc->creator;
              }
          }
          
      }
      
    $i = $i + 1;
  }

Upvotes: 0

Views: 240

Answers (1)

skrilled
skrilled

Reputation: 5371

Since you are dealing with XML content, I found it easier to use SimpleXML instead of DOMDocument. Since each <item> is in the same block as channel you can do a foreach looking for a key of item.

$feed = simplexml_load_file('https://twitrss.me/twitter_search_to_rss/?term=test+this+feed');

foreach ($feed->channel as $row) {
    foreach ($row->children() as $key => $val) {
        if ($key == "item") {
            $ns_dc = $val->children('http://purl.org/dc/elements/1.1/');
            echo $ns_dc->creator;
        }
    }
}

This code outputs the "creator" string you expect.

Upvotes: 2

Related Questions