How to break lines in foreach loop using PHP

Using the following code to display a list of friends from my twitter profile. Id like to load a certain number at a time, say 20, and then provide links for pagination below for the first 1-2-3-4-5 (how many are divided by limit) Last

$xml = simplexml_load_string($rawxml); foreach ($xml->id as $key => $value) { $profile = simplexml_load_file("https://twitter.com/users/$value"); $friendscreenname = $profile->{"screen_name"}; $profile_image_url = $profile->{"profile_image_url"}; echo "<a href=$profile_image_url>$friendscreenname</a><br>"; } 

****** ****** update

 if (!isset($_GET['i'])) { $i = 0; } else { $i = (int) $_GET['i']; } $limit = $i + 10; $rawxml = OauthGetFriends($consumerkey, $consumersecret, $credarray[0], $credarray[1]); $xml = simplexml_load_string($rawxml); foreach ($xml->id as $key => $value) { if ($i >= $limit) { break; } $i++; $profile = simplexml_load_file("https://twitter.com/users/$value"); $friendscreenname = $profile->{"screen_name"}; $profile_image_url = $profile->{"profile_image_url"}; echo "<a href=$profile_image_url>$friendscreenname</a><br>"; } echo "<a href=step3.php?i=$i>Next 10</a><br>"; 

This works, you just need to compensate for the output starting with $i . Thinking of array_slice ?

+4
source share
2 answers

A very elegant solution uses LimitIterator :

 $xml = simplexml_load_string($rawxml); // can be combined into one line $ids = $xml->xpath('id'); // we have an array here $idIterator = new ArrayIterator($ids); $limitIterator = new LimitIterator($idIterator, $offset, $count); foreach($limitIterator as $value) { // ... } // or more concise $xml = simplexml_load_string($rawxml); $ids = new LimitIterator(new ArrayIterator($xml->xpath('id')), $offset, $count); foreach($ids as $value) { // ... } 
+8
source

If you load a complete dataset every time, you can be pretty straight forward and use a for loop instead of foreach:

 $NUM_PER_PAGE = 20; $firstIndex = ($page-1) * $NUM_PER_PAGE; $xml = simplexml_load_string($rawxml); for($i=$firstIndex; $i<($firstIndex+$NUM_PER_PAGE); $i++) { $profile = simplexml_load_file("https://twitter.com/users/".$xml->id[$i]); $friendscreenname = $profile->{"screen_name"}; $profile_image_url = $profile->{"profile_image_url"}; echo "<a href=$profile_image_url>$friendscreenname</a><br>"; } 

You also need to limit $ i to the length of the array, but hopefully you get the gist.

+2
source

All Articles