用php读取txt文件并将结果放入数组中

时间:2014-01-01 10:31:17

标签: php

大家好我需要一个读取txt文件的guid我有一个名为mw2.log的文件,这个文件有多行,每行我有ip:port如下:

1.1.1.1:222
2.2.2.2:3333
3.3.3.3:888
....

使用这种方法我可以读取文件,但我想把每一行都放在数组和seprat ip和port中并返回$ip$port结果,因为我想发送ip和port的抛出POST方法到名为add.php

的其他文件

我的代码是:

<?php

$file = "mw2.log";
$source_file = fopen( $file, "r" ) or die("Couldn't open $file");
if (!feof($source_file)) {
$buffer = fread($source_file, 4096);  // use a buffer of 4KB

//some stuff here

fclose($source_file);
} else {
// error opening the file.
}


//$form_type = 'callofduty4';
//$form_ip = '37.187.71.163';
//$form_c_port = '16044';


$Curl_Session = curl_init('http://127.0.0.1/serverlist/lgsl_files/robot.php');
curl_setopt ($Curl_Session, CURLOPT_POST, 1);
curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "form_type=$form_type&form_ip=$form_ip&form_c_port=$form_c_port");
curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
curl_exec ($Curl_Session);
curl_close ($Curl_Session);

?>

4 个答案:

答案 0 :(得分:0)

为此使用file()explode() ......

<?php
    $ip_arr=file('mw2.log');
    $ips= array();
    $ports=array();
    foreach($ip_arr as $val)
    {
        $val=explode(':',$val);
        array_push($ips,$val[0]);
        array_push($ports,$val[1]);
    }
 print_r($ips);
 print_r($ports);

输出:

Array
(
    [0] => 1.1.1.1
    [1] => 2.2.2.2
    [2] => 3.3.3.3
)
Array
(
    [0] => 222

    [1] => 3333

    [2] => 888
)

答案 1 :(得分:0)

如果您确信这将是一个相对较小且格式正确的文件,那么使用file()可能更容易:

$connectionParams = file("mw2.log");
/*
$connectionParams will look like array('1.1.1.1:222', '2.2.2.2:3333', '3.3.3.3:888') at this point
*/
if ($connectionParams !== false) {
    foreach ($connectionParams as $connectionInfo) {
        // some stuff
    }
} else {
    // error opening the file
}

这是你问的问题吗?

答案 2 :(得分:0)

while (!feof($source_file)) {
    $buffer = fgets($source_file); // read a line    

    $parts = explode(':', $buffer); // seperate ip and ports part
    $ip[] = $parts[0];
    $ports[] = $parts[1];

}
fclose($source_file);

print_r($ip);
print_r($ports);

$ ip现在有ip地址,$ ports有端口。

答案 3 :(得分:0)

我的看法

$lines = file('file.txt');
$output = array();
$count = 0;
foreach($lines as $v) {
    $parts = explode(":", $v);
    $output[$count]['ip'] = $parts[0];
    $output[$count]['port'] = $parts[1];
    $count++; 
}

print_r($output);