Upload and Read a File Using PHP

Hello Thandi ...

Have you heard the one about the goat and the synthetic mouse ... neither have I ...

Okay back to business. Let's get into some geeky stuff.

At some point every software developer will have to read a file for it's contents. This could be reading a list from a CSV or even a SQL file to import data into a database.

In this tutoral we'll be reading a simple text file with just names on it. This will be a list of names, consisting of one name on each row.

Have a look at how the file should look below.

Barnard
proud
moarn
mountain

Now the plan is to try and avoid storing the file in memory as this can be very inefficient for very large files. So we'll be using PHP's SplFileObject object which does not need to load the entire file, can pin-point to a row on the file and only load and read that required part for us.

Also the SplFileObject allows us to manufacture a more object orientated approach to our solution.

Now create that list.txt file will ya. Save it in the directory where your PHP processing file will be.

Now let's get in there, prepare the geek in you. The code below is as simple an implementation of SplFileObject as it gets.

<?php
    $file = 'list.txt';
    $pointer = 1;

    //Create File Stream
    $fileStream = new \SplFileObject($file);
    $fileStream->seek($pointer);

    // Loop until we reach the end of the file.
    while ( ! $fileStream->eof()) {
    // Get The Current Line.
      $currentLine = $fileStream->fgets();
      echo $currentLine.PHP_EOL;
    }
?>

We first load the referral to the file list.txt, then load and inititiate the SplFileObject object.

$fileStream = new \SplFileObject($file);

Once the object is initiated, we then start running through the file. As we run through the file we interact with every row of the file. We do this till the end of the file, after which the stream is closed.

Please note that you can access and control a lot about a file using this tool. Extra extra read all about it here : The SplFileObject class, and school that pretty brain of yours will ya Chad.

"Have you heard the one about the goat and the synthetic mouse ... neither have I ..."

The Village Geek

"Alright, alright, alright ..." - Matthew McConaughey

Well there you have it. Feel free to mess around with the example file or the code itself. Vary the seek pointer, from 1 to 10, put a break in the loop etc.

Go Crazy!!

Talk to you next time ...


Cape Town, South Africa

Comments  (0)

POST A COMMENT
10897 views

Reply to this discussion

You cannot make comments, please login:

Login or Register

Login
Register
Coming Soon ...