Php read file line by line while

How to read line by line in php

when i try to insert each line into my oracle database i get an error stating invalid number, but if have only one line in the file it works fine.

$file = @fopen('file.text', "r") ; // while there is another line to read in the file while (!feof($file)) < // Get the current line that the file is reading $currentLine = fgets($file) ; $currentLine = explode(' ',$currentLine) ; insert($currentLine) ; >fclose($file) ; 

have you tried to simply echo the queries as you go? Chances are something is not being added to the query they way you think it is.

5 Answers 5

$currentLine = trim(fgets($file)); 

It’s possibly failing on the newline/carriage-return at the end of the line.

If not, where is this insert() function defined? Build a debug section that echos or writes out the attempted queries so you can really see the issue.

Читайте также:  Java quiz with answer

Your explode() call is using 9 spaces as a separator, but your file only appears to have 5 spaces between each number. This means your $currentline be a single element array containing the original line, and not separate elements with a number in each.

Either change the number of spaces in the explode call, or change to

$currentLine = preg_split('/\s+/', $currentLine); 

which will split on any number of sequential spaces.

I would double check that there is not a new line at the end of the file. Maybe even double check inside of php that the line read is not blank.

$lineCount=0; // while there is another line to read in the file while (!feof($file)) < $lineCount++; // Get the current line that the file is reading $currentLine = fgets($file); if(trim($currentLine) != '')< $currentLine = explode(' ',$currentLine) ; insert($currentLine) ; echo "Inserted line number $lineCount
"; > else < echo "There was a blank line at line number $lineCount.
"; > >
$lines = explode("\n", str_replace("\r", "", file_get_contents("file.text"))); foreach ($lines as $line)

@jeroen am I missing something or will that not throw an error? file() returns an array, not a string. rtrim() takes a string.

@user570098 i clarified my answer. if you are still getting an error it’s most likely coming from somewhere else.

@Jonathan Kuhn Yes, you would need rtrim on the array elements, not the array, I already noticed and corrected it (see above).

Источник

Read Text Files in PHP

Read Text Files in PHP

  1. Use the fgets() Function to Read Text Files Line by Line in PHP
  2. Use the file() Function to Read Text Files Line by Line in PHP
  3. Use the file_get_contents() and explode() Functions to Read File Line by Line in PHP

This article will introduce methods to read text files line by line in PHP.

Use the fgets() Function to Read Text Files Line by Line in PHP

We can use the fgets() function with a while loop to read text files line by line in PHP. The function returns a line if there is a line, and it returns false if there are no more lines to read. It takes two parameters. The syntax is as the following.

Here, $file resembles a file pointer that points to a successfully opened file. The $length option, optional, denotes the number of bytes to be read.

We can use the open() function to read the file and then use the while loop to loop through each line with the fgets() function. We have a text file abc.txt containing the following contents.

Hi How are you Have a great day 

For example, create a variable $txt_file and write the fopen() function in it. Open the file abc.txt in r mode. Create a line counter variable $a and assign the value 1 to it. Then, create a while loop. Inside the parenthesis of the loop, write the fgets() function with $text_file as the parameter. Assign the function to a $line variable in the loop. Print the $line variable, concatenating it with the $a variable inside the loop body. Increment the $a variable and outside the loop, use the fclose() function to close the file stream.

php $txt_file = fopen('abc.txt','r'); $a = 1; while ($line = fgets($txt_file))   echo($a." ".$line)."
"
;
$a++; > fclose($txt_file); ?>
1 Hi 2 How are you 3 Have a great day 

Use the file() Function to Read Text Files Line by Line in PHP

The file() function reads the whole file into an array. The syntax of the file() function is as below.

file($filename, $flag, $context) 

Here, $filename is the file path to be read. The $flag option is optional and it comprises of various constants such as FILE_USE_INCLUDE_PATH , FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES . The third one is also optional, which defines a context resource.

The file() function returns the whole array if it exists or returns false. We can use the function to read the file context line by line with the helo of the foreach() function. The foreach() function will loop through the entire contents and extract each line individually.

For example, store the filepath in a variable $txt_file . Write a variable $lines and store the file() function on it with $txt_file as the parameter. Next, use the foreach() function to loop through the contents of the file. Use $lines as iterator and $num=>$line as the value. Inside the loop body, print the $num and $line variables.

$txt_file = 'abc.txt';  $lines = file($txt_file); foreach ($lines as $num=>$line)   echo 'Line '.$num.': '.$line.'
'
;
>
Line 0: Hi Line 1: How are you Line 2: Have a great day 

Use the file_get_contents() and explode() Functions to Read File Line by Line in PHP

The file_get_contents() function reads the whole file into a string. It returns the whole file as a string if the contents exist or it returns false. We can specify the file path as the parameter to the function. The explode() function splits a string into an array using a separator. The syntax of the explode() function is as the following.

explode(separator, $string, $limit) 

The separator option is used to separate $string with the number of $limit elements while returning the value. We can combine the file_get_contents() , explode() and foreach() functions to read the text file line by line in PHP.

For example, create a variable $contents and write the file_get_contents() function on it with the filepath in the parameter. Use the explode() function with the \n character as a separator and $contents as the string. Assign the function to a variable $lines . Use the foreach loop to loop $lines as $line . Then, print the $line inside the loop body.

In the example below, the $contents variable returns string. We split it into an array with the \n newline character and printed each line using the loop.

$contents=file_get_contents("abc.txt"); $lines=explode("\n",$contents); foreach($lines as $line)  echo $line.'
'
;
>
Hi How are you Have a great day 

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Источник

6 Ways to Read Files In PHP – Into String, Array, And More!

Welcome to a tutorial on how to read files in PHP. Yep, that is right, how difficult can reading files in PHP be? You will be surprised… It is not as straightforward as some may think.

There are quite a number of ways to read files in PHP:

  1. Read file into a string – $contents = file_get_contents(«FILE»);
  2. Read file into an array – $array = file(«FILE»);
  3. Use cURL to fetch a file from a different server.
    • $curl = curl_init(«http://site.com/»);
    • curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    • $data = curl_exec($curl);
    • curl_close($curl);
  4. Open a file stream and read line-by-line.
    • $stream = fopen(«FILE», «r»);
    • while($line = fgets($stream))
    • Read and directly output – readfile(«FILE»);
    • Directly load a file into the script – include «FILE»; require «FILE»;

That is a quick overview of the common methods, but let us walk through some examples in this guide – Read on!

TLDR – QUICK SLIDES

6 Ways To Read Files In PHP

TABLE OF CONTENTS

READ FILES IN PHP

All right, let us now get into the various ways to read files in PHP.

1) READ FILE INTO A STRING

There is not much rocket science involved here, just take note that file_get_contents() can fetch contents from a file or URL. While this is straightforward, take extra care to not read massive files with this… You will run into an “out of memory” error, and possibly cause some issues on the server.

2) READ FILE INTO AN ARRAY

This is another simple one. But instead of a flat string, file() will read into an array instead, with each element being a different line. Take note again, do not attempt to read large files with this.

3) CURL FETCH

CURL stands for “client URL”, and in layman’s term “server-to-server calls”. Some of you guys may be thinking – What the heck, isn’t this a roundabout way of doing file_get_contents() ? Well no. CURL actually offers a lot of options and controls – It can even fetch files from an FTP server. Will leave the reference links below if you are interested.

4) READ FILE LINE-BY-LINE

 // (C) CLOSE FILE fclose($handle);

The above 3 methods will run into a memory problem when dealing with large files. So to deal with that problem, we can use fgets() and read line-by-line instead.

5) FILE STREAM

This next method is a little different from the rest. Instead of reading a file into strings and arrays, it directly outputs it. Very useful when it comes to forcing a download or transferring huge files.

6) INCLUDE OR REQUIRE

You have probably heard of include and require since day 1 of learning PHP – Yes, they can be used for any file type actually.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this guide, and here are some extras and links that may be useful.

THE SUMMARY

YOUTUBE TUTORIAL

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this short guide. I hope this has helped to solve your file reading yoga issues, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

Источник

Оцените статью