0

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You can also add FILE_SKIP_EMPTY_LINES to the file() call.
Thanks a lot! Definitely seems a lot better than the hackjob I was going to do. Also, was my question really so bad that people had to downvote it? :/ -- Dang. Can't accept your answer for another 2 minutes.
0

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);




?>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.