[SOLVED] JSON and For Loops

I’m trying to create a php script that takes a set of IP addresses and runs them through the ‘ipstack’ online service. I’ve got that part working. However, when I try to get the script to run through all of the ips via a for loop, only the last in the sequence gets processed. How do I fix this? Here’s what I have.

<?php
$access_key = 'some numbers';
$lines = file('source url'); //Get an array of the ip addresses.
for ($i = 0; $i < 100; $i++) {    //Get data
    $ch = curl_init('http://api.ipstack.com/'.$lines[$i].'?access_key='.$access_key.'');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $json = curl_exec($ch);
    echo $json . " \n";
    url_close($ch);

    $api_result = json_decode($json, true);
    $spc = " : ";
    $ip = $api_result['ip'];
    $lat = $api_result['latitude'];
    $lng = $api_result['longitude'];

    $out[$i][0] = $ip;
    $out[$i][1] = $lat;
    $out[$i][2] = $lng;
    $out[$i][3] = $json;
    echo "IP Address " . $i . "\n";
    echo "     " . $lines[$i] . "<br /> \n";
    echo "     " . $lat . "<br /> \n";
    echo "     " . $lng . "<br /> \n";
}

for ($j = 0; $j < 100; $j++) {
    echo " = = = = = = = = = = = = = = = \n";
    echo $out[$j][0] . " \n";
    echo "     " . $out[$j][1] . " \n";
    echo "     " . $out[$j][2] . " \n";
}
?>

look at var_dump($lines); i bet the line breaks are a problem, but there’s a parameter for file() that you can look up in the manual.

That was the issue. I hadn’t thought about the linebreak character until you brought it up. Thank you.

Sponsor our Newsletter | Privacy Policy | Terms of Service