0

I have the following PHP. Basically, I'm getting similar data from multiple pages of a website (the current number of homeruns from a website that has a bunch of baseball player profiles). The JSON that I'm bringing in has all of the URLs to all of the different profiles that I'm looking to grab from, and so I need PHP to run through the URLs and grab the data. However, the following PHP only gets the info from the very first URL. I'm probably making a stupid mistake. Can anyone see why it's not going through all the URLs?

        include('simple_html_dom.php');

        $json = file_get_contents("http://example.com/homeruns.json");

        $elements = json_decode($json);

        foreach ($elements as $element){
                $html = new simple_html_dom();
                $html->load_file($element->profileurl);
                $currenthomeruns = $html->find('.homeruns .current',0);
                echo $element->name, " currently has the following number of homeruns: ", strip_tags($currenthomeruns); 
                return $html;
        }
3
  • Are you sure $elements has multiple records that are different? Sometimes little things like that get you. At first glance you code looks sound.
    – Leeish
    Mar 1, 2013 at 0:07
  • The $elements, which is the JSON, contains 60ish entries at the moment, all in the form { "name":"exampleName","profileurl":"exampleURL" }
    – Kris
    Mar 1, 2013 at 0:20
  • Disregard my comment as I didn't see your return, which was the real issue.
    – Leeish
    Mar 1, 2013 at 0:22

3 Answers 3

3

Wait... You are using return $html. Why? Return is going to break out of your function, thus stopping your foreach.

If you are indeed trying to get the $html out of your function for ALL of the elements, you should push each $html into an array and then return that array after the loop.

2
  • Hm, if I get rid of the return, I get the following: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /home/username/public_html/simple_html_dom.php on line 1333
    – Kris
    Mar 1, 2013 at 0:17
  • Looks like we've solved one question, and it's time for you to ask another about that issue. What is line 1333 by the way? My guess is this one: $html->load_file($element->profileurl);
    – Leeish
    Mar 1, 2013 at 0:23
0

Because you return. return leaves the current method, function, or script, which includes every loop. With PHP5.5 you can use yield to let the function behaves like an generator, but this is definitely out of scope for now.

1
  • Took me too long to see it.
    – Leeish
    Mar 1, 2013 at 0:09
0

Unless your braces are off, you return at the very end of the loop so the loop will never iterate.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.