fscanf

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

fscanfAnaliza un archivo según un formato

Descripción

fscanf(resource $stream, string $format, mixed &...$vars): array|int|false|null

La función fscanf() es similar a la función sscanf(), excepto que toma un archivo como entrada, representado por el recurso stream e interpreta la entrada según el formato format especificado.

Todos los caracteres en blanco de la cadena de formato corresponden a tantos espacios en el flujo de entrada. Esto significa que una tabulación (\t) en la cadena de formato puede reemplazar un espacio simple en el flujo de entrada.

Cada llamada a la función fscanf() lee una línea del archivo.

Parámetros

stream

Resource que apunta a un fichero del sitema que normalmente es creado usando fopen().

format

The interpreted format for string, which is described in the documentation for sprintf() with following differences:

  • Function is not locale-aware.
  • F, g, G and b are not supported.
  • D stands for decimal number.
  • i stands for integer with base detection.
  • n stands for number of characters processed so far.
  • s stops reading at any whitespace character.
  • * instead of argnum$ suppresses the assignment of this conversion specification.

vars

Los valores opcionales a asignar.

Valores devueltos

Si solo se pasan 2 argumentos a la función, el valor analizado será devuelto en forma de un array. Si se pasan argumentos opcionales, la función devolverá el número de valores asignados. Los argumentos opcionales deben ser pasados por referencia.

Si se esperan más subcadenas en el format de las disponibles en string, null será devuelto. En otros casos de error, false será devuelto.

Ejemplos

Ejemplo #1 Ejemplo con fscanf()

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

Ejemplo #2 Contenido del archivo users.txt

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

Ver también

  • fread() - Lectura del archivo en modo binario
  • fgets() - Recupera la línea actual a partir de la posición del puntero de archivo
  • fgetss() - Obtiene un línea desde un puntero a un archivo y elimina las etiquetas HTML
  • sscanf() - Interpreta un string de entrada de acuerdo con un formato
  • printf() - Imprimir una cadena con formato
  • sprintf() - Devuelve un string formateado

add a note

User Contributed Notes 7 notes

up
18
yasuo_ohgaki at hotmail dot com
24 years ago
For C/C++ programmers.

fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
up
7
Bertrand dot Lecun at prism dot uvsq dot Fr
18 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.
up
2
eugene at pro-access dot com
23 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.
up
1
worldwideroach at hotmail dot com
19 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;
}
up
-1
nico at nicoswd dot com
11 years ago
If you want to parse a cron file, you may use this pattern:

<?php

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

}

?>
up
-2
loco.xxx at gmail dot com
18 years ago
to include all type of visible chars you should try:

<?php fscanf($file_handler,"%[ -~]"); ?>
up
-3
robert at NOSPAM dot NOSPAM
22 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.
To Top