1

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

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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>';
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.