2017-02-03 39 views
-1

我正在寻找一种将文本文档的每一行读取为数组元素的方法。在PHP中循环每个数组元素

<?php 

$file = fopen("nums.txt", "r"); 
$i = 0; 
$line = ""; 
$access_key = '1234567890'; 
while (!feof($file)) { 
    $line .= fgets($file); 
} 
$numbers = explode("\n", $line); 

for ($i=0; $i < count($numbers); $i++) { 
    $ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$numbers[$i].''); 

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

    $json = curl_exec($ch); 

    curl_close($ch); 

    $validationResult = json_decode($json, true); 
    echo $numbers[$i] . '</span>' . $validationResult['valid'] . ' ' . $validationResult['country_code'] . ' ' . $validationResult['carrier']; 
} 

fclose($file); 


?> 

任何提示将不胜感激。

干杯!

+0

任何错误,问题,异常行为? –

+0

是的,它应该通过api单独发送每个文件行,但它只是不断发送整个文件:(悲伤熊猫 –

回答

2
$numbers = explode(PHP_EOL, $line); 

这是你想要的吗?

与PHP_EOL

+0

你们很棒,这么简单的解决方案干杯! –

+0

@noob_coding标记为正确:-) – DannyThunder

+0

这仅仅是因为文件和操作系统(windows)'PHP_EOL'具有相同的行尾'\ r \ n'。如果您将脚本移动到Linux,您将再次遇到同样的问题,因为'PHP_EOL'只会是'\ n'。当你知道行尾不使用'PHP_EOL'时。 – AbraCadaver

0
// Get the file content by path. 
$file = file_get_contents($file); 
// Break the file into array of lines. 
$lines = preg_split('/\r*\n+|\r+/', $file); 
// Remove last element as the last \r\n adds an extra element into the array. 
array_pop($lines); 

// Iterate over each line. 
foreach($lines as $line_number => $line_content){ 

    // do something... 
} 
1

更新可以为您节省了大量的工作。阅读到一个数组,然后修整\n和/或\rforeach()

$numbers = array_map('trim', file('nums.txt')); 

foreach($numbers as $number) { 
    // echo $number 
} 
相关问题