Jyotsna Gupta
Jyotsna Gupta

Reputation: 41

Read a CSV in php line by line and store in a variable

I want to read a CSV file in php which is like

203.88.0.0,203.88.31.255  
84.64.0.0,84.71.255.255  
123.63.128.0,123.63.255.255  
112.79.0.0,112.79.255.255  
1.38.0.0,1.39.255.255  
114.31.128.0,114.31.191.255  

and get the output in a variable like:

MAX_checkClient_Ip('10.52.81.60|10.52.81.61', '=^')
or MAX_checkClient_Ip('10.66.40.136|10.66.40.137', '=^')
or MAX_checkClient_Ip('10.99.53.15|10.99.53.21', '=^')
or MAX_checkClient_Ip('10.99.53.143|10.99.53.149', '=^')
or MAX_checkClient_Ip('31.173.64.0|31.173.71.255', '=^')
or MAX_checkClient_Ip('31.173.192.0|31.173.193.255', '=^')
or MAX_checkClient_Ip('31.173.240.0|31.173.243.255', '=^')
or MAX_checkClient_Ip('37.28.160.0|37.28.191.255', '=^')
or MAX_checkClient_Ip('37.29.0.0|37.29.15.255', '=^')

Note that the firstline is not having "or"


public function create_channel()
{
                $file_handle = fopen("IP_SCRIPT.csv", "r");

while (!feof($file_handle) ) {

$line_of_text = fgetcsv($file_handle, 1024);

//print "or MAX_checkClient_Ip('".$line_of_text[0] ."|". $line_of_text[1]."', '=^')\r\n";
$str[]="or MAX_checkClient_Ip('".$line_of_text[0] ."|". $line_of_text[1]."', '=^')\r\n";

}
for($i=0;$i<count($str);$i++)
{
        echo $str[$i];
}


fclose($file_handle);

}

but i get output as

or MAX_checkClient_Ip('203.88.0.0|203.88.31.255', '=^')
or MAX_checkClient_Ip('84.64.0.0|84.71.255.255', '=^')
or MAX_checkClient_Ip('123.63.128.0|123.63.255.255', '=^')
or MAX_checkClient_Ip('112.79.0.0|112.79.255.255', '=^')
or MAX_checkClient_Ip('1.38.0.0|1.39.255.255', '=^')
or MAX_checkClient_Ip('114.31.128.0|114.31.191.255', '=^')
or MAX_checkClient_Ip('|', '=^')

i dont want "or" in first line and also the last line is not needed

Upvotes: 0

Views: 67

Answers (1)

dave
dave

Reputation: 11975

Tweaking your code just a little to move the handling of "or" out of the read loop and into the print loop:

public function create_channel()
{
     $file_handle = fopen("IP_SCRIPT.csv", "r");
     while (!feof($file_handle))
     {
         $line_of_text = fgetcsv($file_handle, 1024);
         $str[]="MAX_checkClient_Ip('".$line_of_text[0] ."|". $line_of_text[1]."', '=^')";
     }
     fclose($file_handle);
     for($i=0; $i<count($str); $i++)
     {
         if ($i > 0) {
              print "or ";
         }
         print $str[$i] . "\n";
     }
}

@Aziz Saleh's suggestion is a good one. The entire for loop could be replaced by:

print implode("\nor ", $str) . "\n";

Upvotes: 2

Related Questions