Category Archives: Php Frequently Asked Questions

Php Read file line by line


Php Read file line by line : For large files we can’t load the full file in memory at a time which will cause memory exhaust errors. To read large file programmatically we should always follow the line by line approach. If you working with an application which has large file in GB or TB or more than that always try to read the files line by line. Here in this tutorial we are going to explain how you can read a big file line by line without causing the memory exhaust error problem.


Php Read file line by line : Read Large File

You can read a large file line by line as below –

Php Read Large file line by line : Example

$file = fopen("bigfile.txt", "r");
if($file){
// if the file is opened successfully 
while(!feof($file)){
    $line = fgets($file);
    //perform action with $line
}
fclose($file);
}else{
  echo "Error while opening the file.";
}

The function feof() is used to get the line no from the file. The above example will open the file and read the file bigfile.txt line by line.

Note : feof() gets the line no from the file pointer. For more detail about the function feof() you can refer – fgets() function.

Remove Last Character From String in Php


Remove Last Character From String in Php : We sometimes need to remove last character from string such as comma(,), semicolon(;) etc. We can remove last character from string in php using the function substr(). There are many ways to remove last character from string we are going to explain some of them with example and demo.


Remove Last Character From String in Php

You can remove the last character using the following – method 1

Remove Last Character From String Using substr() Method 1

Using the substr() function we can remove the last character as

Remove Last Character From String in Php: Remove Last Comma(,)


Try it »

If you run the above example it will produce the following output –

Test

Remove Last Character From String Using rtrim() – Method 2

Using the rtrim() function we can remove the last character as

Remove Last Character From String in Php: Remove Last Comma(,)


Try it »

rtrim($str, “,”) – first parameter is string and second parameter is character you want to remove. rtrim() function removes the character from the right of string if the character is specified otherwise it will remove blank space if found. If you run the above example it will produce the following output –

Test