PHP

Topic: Files

How To Read One Line of Text from a File?

If you have a text file with multiple lines, and you want to read those lines one line at a time, you can use the fgets() function. It reads the current line up to the "\n" character, moves the file pointer to the next line, and returns the text line as a string. The returning string includes the "\n" at the end. Here is a PHP script example on how to use fgets():<?php $file = fopen("/windows/system32/drivers/etc/services", "r");while ( ($line=fgets($file)) !== false ) {  $line = rtrim($line);  print("$line\n");  # more statements...}fclose($file); ?>This script will print:# This file contains port numbers for well-known servicesecho                7/tcpftp                21/tcptelnet             23/tcpsmtp               25/tcp...Note that rtrim() is used to remove "\n" from the returning string of fgets().

Browse random answers: