如果从文本文件输入,PHP ip2long仅拾取最后一个条目

时间:2013-12-18 02:17:20

标签: php fopen fgets

很抱歉,如果之前有人询问,但我的搜索没有提供太多帮助。我在我的脚本中遇到了一些包含PHP内置函数'ip2long'的问题。输入IP地址来自文本文件,该功能仅获取列表中的最后一个地址以进行转换。我在32位计算机上运行脚本,如果这给出了问题的线索。

<?php
$text_file = 'ip.txt';
//begin reading text file
if (($file = fopen($text_file, "r")) !== FALSE) {
    echo "Begin IP Convertion \n";
    while ($line = fgets($file)) {
        echo "$line = " . ip2long($line) . "\n";
    }
} else {echo "No file found \n";}

fclose($file);
?>

以下是ip.txt文件的内容:

127.0.0.1
1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4

运行脚本时的结果:

# php ip.php
Begin IP Convertion 
127.0.0.1
 = 
1.1.1.1
 = 
2.2.2.2
 = 
3.3.3.3
 = 
4.4.4.4 = 67372036
#

-Jon

1 个答案:

答案 0 :(得分:0)

您必须使用trim

之类的内容从字符串中删除换行符
<?php
$text_file = 'ip.txt';
//begin reading text file
if (($file = fopen($text_file, "r")) !== FALSE) {
    echo "Begin IP Convertion \n";
    while ($line = fgets($file)) {
        echo trim($line) . " = " . ip2long(trim($line)) . "\n";
    }
} else {echo "No file found \n";}

fclose($file);
?>