user3767488
user3767488

Reputation: 45

PHP read numbers from a txt file

i'm having some troubles trying to read foat numbers from a txt file. The txt file is this:

10.4 20.5 30.1 40.33 50.12
60.56

i need to store these number in an array, this is the php code that i'm using:

$result = array();
$fp = fopen("./test.txt", "r");
fscanf($fp, "%d\n", $count);
$numbers = explode(" ", trim(fgets($fp)));
foreach ($numbers as &$number)
{
    $number = floatval($number);
    array_push($result,$number);
    echo $php_errormsg;
}
fclose($fp);

But i only get one number, the last one, i tried many ways but i can't solve it by myself at the moment, can anyone help me?

Upvotes: 3

Views: 3691

Answers (5)

mathieu
mathieu

Reputation: 477

$tok = strtok(file_get_contents("./test.txt"),"\n\r\t ");
for($a=array();$tok!==false;$tok=strtok("\n\r\t ")) $a[] = floatval($tok);
var_dump($a);

Upvotes: 0

ggioffreda
ggioffreda

Reputation: 650

If the file contains only numbers and newlines you could try reading it all at once (if it's not huge of course):

$result = explode(" ", str_replace(array(" ", "\n", "\r"), " ", file_get_contents("./test.txt")));

And if you actually need to convert them to floats:

array_walk($result, 'floatval');

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212462

$result = array();
$fp = fopen("./test.txt", "r");
while (($lineData = fgetcsv($fp, 1000, " ")) !== FALSE) {
    $result = array_merge($result, $lineData);
}
fclose($fp)

Upvotes: 1

Rizier123
Rizier123

Reputation: 59701

This should work for you:

(Here I just read your file as a csv file with fgetcsv() with a space as delimiter)

<?php

    $h = fopen("test.txt", "r");

    if($h) {
        while (($data = fgetcsv($h, 1000, " ")) !== FALSE) {
            foreach($data as $num)
                $numbers[] = $num;
        }
        fclose($h);
    }

    print_r($numbers);

?>

output:

Array ( [0] => 10.4 [1] => 20.5 [2] => 30.1 [3] => 40.33 [4] => 50.12 [5] => 60.56 )

Upvotes: 1

Mex
Mex

Reputation: 999

fscanf reads one line from the file, then fgets read the second line.

Try commenting out the fscanf line.

Upvotes: 0

Related Questions