CodeTalk
CodeTalk

Reputation: 3657

XML / Php Read XML, Parse, Output

I am trying to pull data from a source, then parse the data for 3 different fields: "title", "link", "description" and then output the data. However, the loop appears to load the first 10 articles, but then turns into a never ending loop . How do I fix this?

<?php

#Load in File
$xmlUrl ="http://sports.yahoo.com/mlb/rss.xml";
$ConvertToXml = simplexml_load_file($xmlUrl);

# -> Setup XML
$newsStory = $ConvertToXml->channel->item;

# -----> Load News Stories
for($i = 0;i<10; $i++){

    $title=$newsStory[$i]->title;
    //$link=$newsStory[$i]->link;
    $desc=$newsStory[$i]->description;

    echo '<hr>';
    echo 'Title:'.$title.'<br />';
    //echo 'Link:'.$link.'<br />';
    echo 'Description'.$desc.'<br>';
    echo '<hr>';

}

?>

The XML I'm parsing: img

Upvotes: 1

Views: 191

Answers (3)

hakre
hakre

Reputation: 197692

You have created an endless for-loop:

for($i = 0;i<10; $i++){

It is endless because the middle expression is always truthy:

i < 10

It gives: "Notice: Use of undefined constant i - assumed 'i'" so it is:

'i' < 10

And "i" is always smaller than 10 because it evaluates to 0 in that operator context.

Enable error reporting to the highest level on your development platform so that you spot these minor error quickly.

Simple solution is to add the missing $:

for ($i = 0; $i < 10; $i++) {
             ^

But actually in the context of your overall script you might want to prefer a conditional exit:

# -> Setup XML
$newsStories = $ConvertToXml->channel->item;

# -----> Load News Stories
foreach ($newsStories as $index => $newsStory) {

    if ($index === 10) break;

    $title = $newsStory->title;
    //$link = $newsStory->link;
    $description = $newsStory->description;

    echo '<hr>';
    echo 'Title:' . $title . '<br />';
    //echo 'Link:' . $link . '<br />';
    echo 'Description' . $description . '<br>';
    echo '<hr>';
}

Upvotes: 2

Rasmus
Rasmus

Reputation: 8476

It has to be $i<10.. you are using i<10 ..which would end up giving an undefined constant notice too if your error reporting is at the right level

Upvotes: 1

Joshua L&#252;ckers
Joshua L&#252;ckers

Reputation: 112

You forgot a $ in your for loop. for($i = 0;$i<10; $i++) { [..] }

Upvotes: 3

Related Questions