Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 60
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Porady zamieszczone tutaj przez Darka są pomocne w wielu chwilach. Wielokrotnie tworząc jakiś złożony serwis korzystam z tych porad. Można by tworzyć samemu te skrypty, ale tak naprawdę czy nie lepiej jest wziąć skrypt z tej strony i zmodyfikowac go dla swoich potrzeb? Wprawdzie możemy taki skrypt napisać sami, ale po co, skoro stracimy czas na coś, co ktoś juz napisał, przetestował i może zagwarantować, że działa poprawnie. Któryś raz z rzędu opłacam abonament i nie raz jeszcze opłacę. Kawał dobrej roboty i ogrom wiedzy w jednym miejscu.

Piotr Karamański
Design Studio

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

fgets

(PHP 3, PHP 4, PHP 5)

fgets -- Pobiera linię ze wskaźnika pliku

Opis

string fgets ( resource uchwyt [, int długość] )

Zwraca łańcuch o długość - 1 bajtów odczytany z pliku wskazanego przez uchwyt. Czytanie kończy się kiedy przeczytano długość - 1 bajtów lub gdy wystąpi znak nowej linii (jest on dołączany do zwracanego wyniku) lub gdy wystąpi znak końca pliku EOF (którykolwiek przypadek zdarzy się pierwszy). Jeśli nie została określona długość, domyślnie przyjmuje 1k (1024 bajty).

W przypadku błędu, zwraca FALSE.

Główna pułapka:

Osoby przyzwyczajone do semantyki 'C' powinni zauważyć różnicę w sposobie zwracania EOF przez fgets().

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen().

Prosty przykład:

Przykład 1. Czytanie pliku linia po linii

<?php
$uchwyt
= fopen ("/tmp/inputfile.txt", "r");
while (!
feof ($uchwyt)) {
  
$buffer = fgets($uchwyt, 4096);
   echo
$buffer;
}
fclose ($uchwyt);
?>

Notatka: Parametr długość stał się opcjonalny w PHP 4.2.0 jeśli został pominięty, to powinien przyjąć wartość 1024. W PHP 4.3, pominięcie długość powoduje odczytywanie ze strumienia do chwili osiągnięcia końca lini, Jeśli większość lini w pliku jest dłuższa od 8KB, dużo efektywniejsze jest podanie maksymalnej długości linii.

Notatka: Funkcja jest binaarnie bezpieczna od PHP 4.3. Poprzednie wersje nie są binarnie bezpieczne.

Notatka: W przypadku problemów z rozpoznawaniem znaków końca linii przez PHP przy czytaniu plików stworzonych lub znajdujących się na komputerach Macintosh, może pomóc włączenie dyrektywy konfiguracji auto_detect_line_endings.

Patrz także: fread(), fgetc(), stream_get_line(), fopen(), popen(), fsockopen() i socket_set_timeout().




User Contributed Notes

ecvej
04-Jan-2006 10:20

I would have expected the same behaviour from these bits of code:-

<?php

/*This times out correctly*/
while (!feof($fp)) {
   echo
fgets($fp);
}

/*This times out before eof*/
while ($line=fgets($fp)) {
   echo
$line;
}

/*A reasonable fix is to set a long timeout*/
stream_set_timeout($fp, 180);
while (
$line=fgets($fp)) {
   echo
$line;
}
?>


hackajar <matt> yahoo <trot> com
05-Dec-2005 09:17

When working with VERY large files, php tends to fall over sideways and die. 

Here is a neat way to pull chunks out of a file very fast and won't stop in mid line, but rater at end of last known line.  It pulled a 30+ million line 900meg file through in ~ 24 seconds.

NOTE:
$buf just hold current chunk of data to work with.  If you try "$buf .=" (note 'dot' in from of '=') to append $buff, script will come to grinding crawl around 100megs of data, so work with current data then move on!

//File to be opened
$file = "huge.file";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;

while(!feof($fp)) {
   $rbuf = fread($fp, $read);
   for($i=$read;$i > 0 || $n == chr(10);$i--) {
       $n=substr($rbuf, $i, 1);
       if($n == chr(10))break;
       //If we are at the end of the file, just grab the rest and stop loop
       elseif(feof($fp)) {
           $i = $read;
           $buf = substr($rbuf, 0, $i+1);
           break;
       }
   }
   //This is the buffer we want to do stuff with, maybe thow to a function?
   $buf = substr($rbuf, 0, $i+1);
   //Point marker back to last \n point
   $part = ftell($fp)-($read-($i+1));
   fseek($fp, $part);
}
fclose($fp);


kpeters AT-AT monolithss DEE OH TEE com
01-Dec-2005 02:51

It appears that fgets() will return FALSE on EOF (before feof has a chance to read it), so this code will throw an exception:

while (!feof($fh)) {
  $line = fgets($fh);
  if ($line === false) {
   throw new Exception("File read error");
  }
}


dandrews OVER AT 3dohio DOT com
07-Jan-2005 08:11

Saku's example may also be used like this:

<?php
 
@ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); // the @ suppresses errors so you have to test the pointer for existence
  
if ($pointer) {
     while (!
feof($pointer)) {
        
$preTEXT = fgets($pointer, 999);
        
// $TEXT .= $preTEXT;  this is better for a string
      
$ATEXT[$I] = $preTEXT// maybe better as an array
      
$I++;
     }
    
fclose($pointer);
   }
?>


angelo [at] mandato <dot> com
19-Nov-2004 03:43

Sometimes the strings you want to read from a file are not separated by an end of line character.  the C style getline() function solves this.  Here is my version:
<?php
function getline( $fp, $delim )
{
  
$result = "";
   while( !
feof( $fp ) )
   {
      
$tmp = fgetc( $fp );
       if(
$tmp == $delim )
           return
$result;
      
$result .= $tmp;
   }
   return
$result;
}

// Example:
$fp = fopen("/path/to/file.ext", 'r');
while( !
feof($fp) )
{
  
$str = getline($fp, '|');
  
// Do something with $str
}
fclose($fp);
?>


lelkesa
04-Nov-2004 11:54

Note that - afaik - fgets reads a line until it reaches a line feed (\\n). Carriage returns (\\r) aren't processed as line endings.
However, nl2br insterts a <br /> tag before carriage returns as well.
This is useful (but not nice - I must admit) when you want to store a more lines in one.
<?php
function write_lines($text) {
 
$file = fopen('data.txt', 'a');
 
fwrite($file, str_replace("\n", ' ', $text)."\n");
 
fclose($file);
}

function
read_all() {
 
$file = fopen('data.txt', 'r');
  while (!
feof($file)) {
  
$line = fgets($file);
   echo
'<u>Section</u><p>nl2br'.($line).'</p>';
  }
 
fclose($file);
}
?>

Try it.


06-Sep-2004 12:05

If you need to simulate an un-buffered fgets so that stdin doesnt hang there waiting for some input (i.e. it reads only if there is data available) use this :
<?php

  
function fgets_u($pStdn) {

          
$pArr = array($pStdn);

       if (
false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
           print(
"\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
           return
FALSE;
       } elseif (
$num_changed_streams > 0) {
               return
trim(fgets($pStdn, 1024));
       }
          
   }

?>


rstefanowski at wi dot ps dot pl
12-Aug-2004 06:03

Take note that fgets() reads 'whole lines'. This means that if a file pointer is in the middle of the line (eg. after fscanf()), fgets() will read the following line, not the remaining part of the currnet line. You could expect it would read until the end of the current line, but it doesn't. It skips to the next full line.


timr
17-Jun-2004 04:13

If you need to read an entire file into a string, use file_get_contents().  fgets() is most useful when you need to process the lines of a file separately.


Saku
05-Jun-2004 02:47

As a beginner I would have liked to see "how to read a file into a string for use later and not only how to directly echo the fgets() result. This is what I derived:
<?php
 
@ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); // the @ suppresses errors so you have to test the pointer for existence
  
if ($pointer) {
     while (!
feof($pointer)) {
        
$preTEXT = fgets($pointer, 999);
        
$TEXT = $TEXT . $preTEXT;
     }
    
fclose($pointer);
   }
?>


flame
22-May-2004 05:44

fread is binary safe, if you are stuck with a pre 4.3 version of PHP.


Pete
23-Feb-2004 01:35

If you have troubles reading binary data with versions <= 4.3.2 then upgrade to 4.3.3
The binary safe implementation seems to have had bugs which were fixed in 4.3.3


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt