(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fscanfInterpreta a leitura de um arquivo de acordo com um formato


mixed fscanf ( resource $handle , string $formato [, mixed &$... ] )

A função fscanf() é semelhante à sscanf(), mas usa como entrada um arquivo associado com o handle e interpreta a entrada de acordo com o formato especificado, o qual é descrito na documentação da sprintf().

Qualquer espaço em branco na string do formato combina com quaisquer outros espaços no stream de entrada. Isto significa que até uma tabulação \t na string do formato combina com um caracter de espaço simples no stream de entrada.



Um ponteiro de arquivo tipo resource tipicamente criado por fopen().


O formato especificado como descrito na documentação de sprintf().


Variáveis opcionais onde definir os valores.

Valor Retornado

Se somente dois parâmetros forem passados pra essa função, os valores interpretados serão retornados como um array. Do contrário, se parâmetros opcionais forem passados, a função retornará o número de valores definidos. Os parâmetros opcionais devem ser passados por referência.


Versão Descrição
4.3.0 Antes do PHP 4.3.0, o maior número de caracteres lidos do arquivo era 512 (ou o primeiro \n, o que viesse primeiro). Agora, linhas de qualquer comprimento são lidas e interpretadas.


Exemplo #1 Exemplo de fscanf()

while (
$userinfo fscanf($handle"%s\t%s\t%s\n")) {
    list (
$name$profession$countrycode) = $userinfo;
//... fazer algo com os valores

Exemplo #2 Conteúdo de users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

Veja Também

  • fread() - Leitura binary-safe de arquivo
  • fgets() - Lê uma linha de um ponteiro de arquivo
  • fgetss() - Ler uma linha de um ponteiro de arquivo e retira as tags HTML
  • sscanf() - Interpreta a entrada de uma string de acordo com um formato
  • printf() - Mostra uma string formatada
  • sprintf() - Retorna a string formatada

add a note add a note

User Contributed Notes 10 notes

nico at nicoswd dot com
2 years ago
If you want to parse a cron file, you may use this pattern:


while ($cron = fscanf($fp, "%s %s %s %s %s %[^\n]s"))


yasuo_ohgaki at hotmail dot com
14 years ago
For C/C++ programmers.

fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
eugene at pro-access dot com
13 years ago
If you want to read text files in csv format or the like(no matter what character the fields are separated with), you should use fgetcsv() instead. When a text for a field is blank, fscanf() may skip it and fill it with the next text, whereas fgetcsv() correctly regards it as a blank field.
loco.xxx at gmail dot com
9 years ago
to include all type of visible chars you should try:

<?php fscanf($file_handler,"%[ -~]"); ?>
robert at NOSPAM dot NOSPAM
13 years ago
actually, instead of trying to think of every character that might be in your file, excluding the delimiter would be much easier.

for example, if your delimiter was a comma use:


instead of:

%[a-zA-Z0-9.| ... ]

Just make sure to use %[^,\n] on your last entry so you don't include the newline.
Bertrand dot Lecun at prism dot uvsq dot Fr
8 years ago
It would be great to precise in the fscanf documentation
that one call to the function, reads a complete line.
and not just the number of values defined in the format.

If a text file contains 2 lines each containing 4 integer values,
reading the file with 8 fscanf($fd,"%d",$v) doesnt run !
You have to make 2
fscanf($fd,"%d %d %d %d",$v1,$v2,$v3,$v4);

Then 1 fscanf per line.
worldwideroach at hotmail dot com
10 years ago
Yet another function to read a file and return a record/string by a delimiter.  It is very much like fgets() with the delimiter being an additional parameter.  Works great across multiple lines.

function fgetd(&$rFile, $sDelim, $iBuffer=1024) {
    $sRecord = '';
    while(!feof($rFile)) {
        $iPos = strpos($sRecord, $sDelim);
        if ($iPos === false) {
            $sRecord .= fread($rFile, $iBuffer);
        } else {
            fseek($rFile, 0-strlen($sRecord)+$iPos+strlen($sDelim), SEEK_CUR);
            return substr($sRecord, 0, $iPos);
    return false;
james at zephyr-works dot com
14 years ago
fscanf works a little retardedly I've found. Instead of using just a plain %s you probably will need to use sets instead. Because it works so screwy compared to C/C++, fscanf does not have the ability to scan ahead in a string and pattern match correctly, so a seemingly perfect function call like:

fscanf($fh, "%s::%s");

With a file like:


Will not work. When fscanf looks for a string, it will look and stop at nothing except for a whitespace so :: and everything except whitespace is considered part of that string, however you can make it a little smarter by:

fscanf($fh, "%[a-zA-Z0-9,. ]::%[a-zA-Z0-9,. ]" $var1, $var2);

Which tells it that it can only accept a through z A through Z 0 through 9 a comma a period and a whitespace as input to the string, everything else cause it to stop taking in as input and continue parsing the line. This is very useful if you want to get a sentence into the string and you're not sure of exactly how many words to add, etc.
hdh265 at 163 dot com
7 months ago
The use of PHP code in the ACM submission
Here is a sample solution for problem 1001 using PHP:
while (fscanf(STDIN, "%d%d", $a, $b) == 2) {
    print (
$a + $b) . "\n";
arentzen at religion dot dk
8 years ago
If you want fscanf()to scan one variable in a large number of lines,  e.g an Ipadress in a line with more variables, then use fscanf with explode()
= "somefile.txt";
$fp = fopen($filename, "r") or die ("Error opening file! \n");
$u = explode(" ",$line); // $u is the variable eg. an IPadress
while ($line = fscanf($fp,"%s",$u)) {
preg_match("/^$u/",$_SERVER['REMOTE_ADDR'])) {$badipadresss++;} // do something and continue scan
Besides, fscanf()is much faster than fgets()
To Top