【问题标题】:Read a CSV in php line by line and store in a variable逐行读取php中的CSV并存储在变量中
【发布时间】:2015-08-04 05:25:49
【问题描述】:

我想在php中读取一个CSV文件,就像

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  

并在如下变量中获取输出:

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', '=^')

注意第一行没有“或”


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

}

但我得到的输出为

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('|', '=^')

我不想在第一行使用“或”,也不需要最后一行

【问题讨论】:

  • 常规做法是包含您迄今为止尝试过的内容,而不是仅仅寻求解决方案。阅读how to askmcve

标签: php file csv


【解决方案1】:

稍微调整您的代码,将“或”的处理移出读取循环并进入打印循环:

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 的建议很好。整个for 循环可以替换为:

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

【讨论】:

  • 为什么不在第一个循环中使用换行符并进行内爆而不是创建另一个循环?
猜你喜欢
  • 2016-06-19
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
相关资源
最近更新 更多