PHP: Run through multiple URLs and display their content - php

Let's say we have an URL looking something like this.
http://domain.com/index.php?p=1&u=A1b2C3d4E5f6G7h8I9j
The number span after ?p= goes from 1 to 999 and the rest is unchanged.
Every URL contains one short line of text.
What would a script look like which can run through all 999 URLs and display their contents?

It would be easy. You can use the FOR LOOP.
<?php
for($i=1; $i < 1000; $i++) {
echo file_get_contents('http://domain.com/index.php?p=' . $i . '&u=A1b2C3d4E5f6G7h8I9j');
}
Documentations:
For Loop
file_get_contents() method

This is going to be resource intensive. But taking a shot in the dark, this should work:
<?php
$urlContent = array();
$urlStart = 'http://domain.com/index.php?p=';
$urlEnd = '&u=A1b2C3d4E5f6G7h8I9j';
$count = 1;
while($count <= 999){
$urlContent[$count] = file_get_contents($urlStart.$count.$urlEnd);
$count++;
}
foreach($urlContent as $content){
echo $content.'\n';
}
?>
This code is Untested

Related

Remove the 0 from for results

Currently, I'm messing around with SoundCloud's API and it's returning something that looks like this.
0. HotBox Michael da Vinci Prod Free P.mp3
https://api.soundcloud.com/tracks/373337717/stream?client_id=OURID
1. LSSR Chris P Prod Jake Knight.mp3
https://api.soundcloud.com/tracks/373336760/stream?client_id=OURID
Which is working properly as how the code appears, here it is how I'm printing out the results (very messy but I'm just messing around)
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
print '<br>'; print '<br>';
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
print ''.$i.'. '.$title.'.mp3';
print '<br>';
print $stream = ''.$b2.'?client_id=OURID';
}
Now what I'm wondering is how under every circumstance can we make the 0. return as a 1. and continue counting upwards until reaching the end of the for loop, not removing the 0. data but only changing the number.
I recommend a foreach loop with the $i counter declared in the loop and just increment it as you go.
Untested code:
foreach ($house as $i=>$row){
echo '<br><br>',++$i,'. ',preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title'])),".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
p.s. I've improved the regex pattern and eliminated all single-use variable declarations. You can break this up over many lines if you prefer.
If you want to avoid the first iteration's double break tags...
foreach ($house as $i=>$row){
if($i) echo '<br><br>'; // if $i is not 0
echo ++$i,'. ';
echo preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title']));
echo ".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
Based on the comments and your description of what you are trying to do, it sounds like you just need to add another iteration variable:
# Add another variable
$a = 1;
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
echo '<br><br>';
# Here you have the $a show up starting at 1
echo ''.$a.'. '.$title.'.mp3<br>';
echo $stream = ''.$b2.'?client_id=OURID';
# Auto increment here
$a++;
}

PHP echo line X times different text

Title might not make complete sense, couldn't think of a way to explain it so I will do a mock PHP example.
<?php
$startNumber = 1;
$endNumber = 15;
$fileExt = '.jpg';
?>
And then on the page it will echo from the $startNumber to the $endNumber in something like a foreach
<?php echo("<img src=\"#.jpg\">"); ?>
Hope this is making sense...
I'd also like to point out that the numbers < 10 start with a 0 so it will need to be in the image source link.
echo is not a function, it's a language construct. Don't use ().
Also you need to use a loop like for() to do that (Also see sidenote of Fred -ii).
$endNumber = 15;
for($i = 1; $i <= $endNumber; $i++) {
if($i < 10) {
$i = "0".$i;
}
echo "<img src=\"".$i.".jpg\" />";
}
If this is not what you asked, add more information.

How can I loop through an array, starting at an offset and looping round again?

Newb question: I'm using a foreach loop to get items from an array.
I need to start looping at an offset number- (I'm using a $i variable to do this, no problem).
But when my foreach reaches the end of the array I want it to start going through the array again until it reaches the offset number.
I need to do this so I can have a user open any image in an artist's portfolio and have this image used as the first image presented in a grid of thumbnail icons , with all the other images subsequently populating the rest of the grid.
Any ideas?
Please bear in mind I'm new to PHP! :)
See below for an example of my current code...
$i=0;
$limit=50;// install this in the if conditional with the offset in it (below) to limit the number of thumbnails added to the page.
$offset=$any_arbitrary_link_dependant_integer;
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};// end of add thumbnails loop.
$i = 0;
$limit = 50;
$offset = $any_arbitrary_link_dependant_integer;
$count = count($portfolio_image_array);
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit && $i < ($count - $offset)) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};
Only thing I added was a $count variable.
Edit: If your array starts at 0 I would suggest you put the $i++; at the end of your foreach loop.
A simple method is to use two separate numeric for loops, the first going from offset to end, and the second going from beginning to offset.
<?php
// Create an example array - ignore this line
$example = array(1,2,3,4,5,6);
$offset = 3;
// Standard loop stuff
$count = count($example);
for($i = $offset; $i < $count; $i++)
{
echo $example[$i]."<br />";
}
for($i = 0; $i < $offset; $i++)
{
echo $example[$i]."<br />";
}
?>
This is also almost certainly cheaper than doing multiple checks on every single element in the array, and it expresses exactly what you are trying to do to other programmers who look at this code - including yourself in 2 weeks time.
Edit: depending on the nature of the array, in order to use numeric keys you may first need to do $example = array_values($portfolio_image_array);.
Using Answer Question to force StackOverflow to let me post a decent length of text!
OK #Mark Walet et al, not sure how to post correctly on this forum yet but here goes. I got the issue sorted as follows:
$i=0;
$offset=$image_to_display_number;
$array_length = count($portfolio_image_array);
// FIRST HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from offset (chosen image) to end.
if ($i >= $offset && $i <= $array_length) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
$t_total++;// update thumbnail total count.
}
$i++;
}// end of foreach loop 1.
$looped=true;// Just FYI.
$i=0;// Reset.
// SECOND HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from beginning to offset.
if ($i < $offset) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
}
$i++;
}// end of foreach loop 2.
Thankyou so much for all the help!
:)
as #arkascha suggested use modulo operator
<?php
$example = array(1,2,3,4,5,6);
$count = count($example);
$offset = 3;
for($i = 0; $i < $count; $i++) {
$idx = ($offset + $i) % count
echo $example[$idx]."<br />";
}
?>

Create a custom array in PHP

I've played around with a personal project regarding a website listing PC games by year of releasing etc. (the topic it is not so important i guess) using the following structure for the links:
http://localhost/
http://localhost/?g=15
http://localhost/?g=30
http://localhost/?g=45
Like it is seen, I've display 15 games per page. What am I working right now is displaying the above links using php in a specific manner for each page (thumbnails, links, etc.):
$arr = array("","?g=15","?g=30","?g=45","?g=60","?g=75","?g=90");
foreach ($arr as $page) {
$link = 'http://localhost/' . (string)$page;
// do stuff to each page link
}
I am very satisfied with how it goes so far but I am wondering if there is a way to create the array automatically not requiring me to manually write the string, just specify the last multiple of 15 for example. I searched the web but I haven't find something concludent or maybe I don't express myself clear enough that's why any help is more than welcomed.
echo 'http://localhost';
for ($i = 15; $i < $max; $i += 15) {
echo "http://localhost/?g=$i";
}
In practice $max is calculated by how many entries there are, which is something you usually figure out from querying a database. Hope this points you in the right direction though.
You can easily generate your array:
<?php
$arr = array('');
$max = 5;
for($i = 0; $i < $max; ++$i) {
$arr[] = '?g='.($i*15);
}
?>
Thry this and tell me if it helps
$links = array();
$links[] = 'http://localhost/';
$multiplier = 5; //the mutiplier, number of links to provide
for ($i = 1; $i < $multiplier; $i++)
{
$links[$i] = 'http://localhost/?g='.(15*$i);
// do here what you want with $links[$i]
}
print_r($links);

there's any way to use foreach with AND?

foreach(($_POST["msg"] as $mg) AND ($_POST["control"] as $id))
{
echo $mg;
echo $id;
}
i need make something like that, any way to do? i'm trying to get 10 mysql records and edit all of them
No, that won't work. The closest thing I can see to what you're trying to do is:
for($i = 0; $i < count($_POST["msg"]); $i++) {
echo $_POST["msg"][$i];
echo $_POST["control"][$i];
}
Assuming that "msg" and "control" will always contain the same amount of items.
Assuming both $_POST['msg'] and $_POST['control'] are actually arrays, have numeric keys (thanks #iMoses), and have the same length, you could use a for loop -
for ($i = 0; $i < count($_POST["msg"]); $i++){
$mg = $_POST['msg'][$i];
$id = $_POST['control'][$i];
}

Categories