|
|
 |
fscanf (PHP 4 >= 4.0.1, PHP 5) fscanf -- Procesa la entrada desde un archivo de acuerdo a un
formato Descripciónmixed fscanf ( resource gestor, string formato [, mixed &...] )
La función fscanf() es similar a
sscanf(), pero toma su entrada desde un
archivo asociado con gestor e interpreta
la entrada de acuerdo al formato
especificado, el cual es descrito en la documentación de
sprintf(). Si sólo se pasan dos
parámetros a esta función, los valores procesados
serán devueltos como una matriz. De otro modo, si se pasan
parámetros opcionales, la función devolverá
el número de valores asignados. Los parámetros
opcionales deben ser pasados por referencia.
Cualquier espacio en blanco en la cadena de formato crea una
correspondencia con cualquier espacio en blanco en la secuencia
de entrada. Esto quiere decir que incluso una tabulación
\t en la cadena de formato puede coincidir con
un caracter de espacio sencillo en la secuencia de entrada.
Ejemplo 1. Ejemplo de fscanf() |
<?php
$gestor = fopen("usuarios.txt","r");
while ($info_usuario = fscanf($gestor, "%s\t%s\t%s\n")) {
list ($nombre, $profesion, $cod_pais) = $info_usuario;
}
fclose($gestor);
?>
|
|
Ejemplo 2. Contenido de usuarios.txt javier argonauta pe
hiroshi escultor jp
robert desempleado us
luigi florista it |
|
Nota:
Antes de PHP 4.3.0, el máximo número de caracteres
leÃdos desde el archivo era 512 (o hasta el primer \n, lo
que primero ocurriera). A partir de PHP 4.3.0 se leerán y
analizarán lÃneas de longitudes arbitrariamente
grandes.
Vea también
fread(), fgets(),
fgetss(), sscanf(),
printf(), y sprintf().
loco.xxx at gmail dot com
24-Jul-2006 12:46
to include all type of visible chars you should try:
fscanf($file_handler,"%[ -~]");
worldwideroach at hotmail dot com
14-Jul-2005 09:33
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;
}
rudigreen at gmail dot com
01-Jul-2005 03:43
I have a function for reading delimited files, it works for multiple lines too (i think...)
<?
function file_read_delim($fh,$delim,$callback,$len=1024)
{
$rec = '';
while(!feof($fh))
{
$buf = fread($fh,$len);
if(strpos($buf,$delim) === false)
{
$rec .= $buf;
}
else
{
$strs = explode($delim,$buf);
foreach ($strs as $ele)
{
$rec .= $ele;
call_user_func($callback,$rec);
$rec = '';
}
}
}
}
$fh = fopen($filename,'r');
if(!$fh)
{
die 'Could not open file for reading';
}
file_read_delim($fh,'-','cb');
fclose($fh);
function cb($rec)
{
echo "$rec \n";
}
?>
me at hesterc dot fsnet dot co dot uk
25-May-2004 07:03
I have a simpler method I use to parse delimited text. Using the data posted by gozer at fanhunter dot com, here is my script. Maybe it is faster?
<?php
$fp = fopen ("sections.dat","r");
if (!$fp) {echo "<p>Unable to open remote file.</p>"; exit;}
while (!feof($fp)):
$line = fgets($fp, 2048);
$out = array($line);
list ($id, $name, $description, $language, $directory, $id_uplevel, $order, $hassubsection) = split ("\|", $out[0]);
echo "$id-$name-$description-$language-$directory-
$id_uplevel-$order-$hassubsection<br />\n";
$fp++;
endwhile;
fclose($fp);
?>
Notes:
Avoid the php extension on a data file - it will cause PHP to parse the file, but there is no PHP in it.
The "2048" value on line 2 of the loop is set for long lines. 1024 works fine, but I had to increase it with a large database I use a similar script to read.
You don't need to open and close the speech marks (as in gozer at fanhunter dot com's example) in the echo line, just use the variables inbetween the dashes.
(Remove the line break halfway through the echo line - it is just there for this forum.)
matt at mattsinclair dot com
21-Jan-2004 12:36
A better way to use fscanf() would be this:
<?php
$handle = fopen("users.txt", "r");
while (!feof($handle)) {
$userinfo = fscanf($handle, "%s\t%s\t%s\n");
if ($userinfo) {
list ($name, $profession, $countrycode) = $userinfo;
}
$userinfo=NULL;
}
fclose($handle);
?>
as you can see, instead of waiting for fscanf() to fail to return a value... it waits for the the pointer to get to the end of the file... this way, if for some reason one of your lines does not match your expression, it will not kill the loop. it will simply go on to the next line.
robert at NOSPAM dot NOSPAM
24-Oct-2002 04:08
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.
ruiner911 at yahoo dot com
15-Aug-2002 01:01
Clear the variables before you scan them in. As a programmer this should have been very apparent. Goof.
eugene at pro-access dot com
16-Mar-2002 12:39
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.
gozer at fanhunter dot com
07-Mar-2002 06:53
Hi,
A few days ago we got multiple mySQL crashes due to a hardware failure and other processes running.
While we thought it could be the mySQL daemon overloaded, we started looking for alternate ways to get our little databases working so we started using fscanf to parse files.
We ran into multiple problems due to the whitespace and other characters that were in our database. Finally, we made it to work using sets as james@zephyr-works.com remarked.
Our final function is:
function get_sections($include_dir){
$filename = $include_dir . "sections.dat.php";
$datafile = fopen ($filename ,"r");
while ($sectioninfo = fscanf ($datafile, "%[0-9]|%[a-zA-Z0-9@&;:,. /!?-]|%[a-zA-Z0-9@&;:,. /!?-]|%[a-zA-Z]|%[a-zA-Z0-9@/?&;.+=-]|%[0-9]|%[0-9]|%[0-9]\n")) {
list($id, $name, $description, $language, $directory, $id_uplevel, $order, $hassubsection) = $sectioninfo;
// Show output
echo $id . "-" . $name. "-" . $description . "-" . $language . "-" . $directory . "-" . $id_uplevel . "-" . $order . "-" . $hassubsection . "<br>\n";
}
fclose($datafile);
}
The contents of sections.dat.php (for example):
1|home|Página principal de Fanhunter.|castellano|==|0|0|0
2|fanhunter|Sección principal dedicada al universo Fanhunter.|castellano|fanhunter/|1|0|0
3|outfan|Sección principal dedicada al universo Outfan.|castellano|outfan/|1|0|0
4|fanpiro|Sección principal dedicada al universo Fanpiro.|castellano|fanpiro/|1|0|0
5|tienda|La tienda de Fanhunter.|castellano|tienda/|1|0|0
6|the zone|Sección principal Miscelánea.|castellano|thezone/|1|0|0
7|flfcn|Sección principal dedicada a Fan Letal/Fan con Nata.|castellano|fanletal/|1|0|0
8|foro|Nuestro foro de discusión.|castellano|foro/|1|0|0
9|chat|Sección para chatear.|castellano|chat/|1|0|0
10|links|Sección recopilatoria de enlaces de interés a otras páginas.|castellano|links/|1|0|0
Note: The '==' in directory means no directory needed to be specified.
Pay attention to linebreaks, as this forum puts some of them into the code I pasted.
Good luck guys.
james at zephyr-works dot com
08-Jul-2001 12:29
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:
user::password
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.
yasuo_ohgaki at hotmail dot com
12-Mar-2001 11:59
For C/C++ programmers.
fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
| |
| | Citas célebres | En los momentos de crísis, la imaginación es más importante que el conocimiento. Albert Einstein Físico estadounidense (1879-1955) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Abogados | | Confesiones | - Y usted, ¿abandonó a su familia?
- No, le explico, es que yo era jardinero...
- ¿Y...?
- Pues que a mis hijos los dejaba regados y a mi mujer plantada. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|