Rob
Rob

Reputation: 8101

Exploding array values in PHP

I'm working on a script that connects to a server using proxies, going through the list until it finds a working proxy.

The list of proxies is like this:

127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080
127.0.0.1:8080

Of course, it's not the same IP and port over and over. Now, originally I was just going to use file() to put them all into an array, but that leaves an array with the values including the full line, obviously.

Ideally what I'd like is an array like

"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,
"127.0.0.1" => 8080,

But I'm not sure of the easiest (and most efficient) way to do that. Any suggestions?

Upvotes: 0

Views: 783

Answers (2)

Shahzab Asif
Shahzab Asif

Reputation: 491

Use Following Code

<?php

$data = "127.0.0.1:8080
    127.0.0.1:8080
    127.0.0.1:8080
    127.0.0.1:8080
    127.0.0.1:8080
    127.0.0.1:8080
    127.0.0.1:8080";


    $urls = explode("\n",$data);

    $new_data = array();
    foreach($urls as $url){
        if($url!=""){
            $url_parts = explode(":",$url);
            $new_data[] = array($url_parts[0]=>$url_parts[1]);
        }
    }

    print_r($new_data);




?>

Upvotes: 0

Mike B
Mike B

Reputation: 32155

Loop over the file and do some parsing:

$path = './file.txt';

$proxies = array();
foreach(file($path, FILE_SKIP_EMPTY_LINES) as $line) {
  $proxy = trim($line);
  list($ip, $port) = explode(':', $proxy);

  $proxies[$ip] = $port;
}

var_dump($proxies);

Should note that your 'expected' example is invalid array notation as the key is the same for every element. But I just assumed you were going for formatting.

Upvotes: 4

Related Questions