a53-416
a53-416

Reputation: 3955

How to read entire line (string) using fscanf?

I have a text file that I'm reading line by line. When I get to the line that's a string (six words long) I want to read it and assign it to the variable $str, so I do this:

fscanf($handle, "%s", $str);

//The line is "one two three four"

echo $str ; // prints out "one"

However, it only saves the first word of the string, due to the spaces after each word. How do I capture the whole thing?

Upvotes: 5

Views: 4938

Answers (3)

Serge P
Serge P

Reputation: 1863

It's old question, but for googlers:

To read a whole line with fscanf(), use "%[^\n]". In fscanf(), $[^characters] means to match any sequence of characters that isn't in the set between the brackes (it's similar to [^characters]* in a regular expression). So this matches any sequence of characters other than newline. See http://php.net/manual/en/function.sscanf.php#56076

from PHP fscanf vs fgets

Upvotes: 6

Siddhesh Yadav
Siddhesh Yadav

Reputation: 1

I hope the following code snippet works,

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($handle);
?>

Upvotes: 0

Sreehari Annam
Sreehari Annam

Reputation: 15

sometimes fscanf will not read the entire line if the input string contains the character "n". So it is always better to use "%[^]" for reading the entire line in PHP through fscanf

Upvotes: -2

Related Questions