Read And Write From a File Line by Line in PHP

Hello Friends,
This is a simple example which demonstrates how one can write into a file line by line data in json format and read from that file again line by line.

1. Create a file index.php and write the following code there.

$db=new db();

$db->insert(“insert into tablename values(‘sudhanshu’, ’22’, ‘male’)”);
    foreach($result AS $k => $re){
        if($k!=” && $re!=”){
        echo “

".$k.' :: '.$re."

    echo ‘na’;

2. Create a file db.php

class db{
 public function insert($query){
 private function filestore($q, $qstatus=true){
              global $profiler;
              $arr=explode(‘ ‘, trim($q));
              if($getfirst==’show’ || $getfirst==’select’ || $gethird==’errorlog’){
                  return false;
              if(!file_exists($filedir)) //part A
                    mkdir($filedir);//directory created
                  $fhandle= fopen($fileaddress,’a’);
                  // Let’s make sure the file exists and is writable first.
              if (is_writable($fileaddress)) {
               $profiler->add(‘Now Storing the queries in File[‘.$fileaddress.’]’);
                      // The file pointer is at the bottom of the file hence
                      // that’s where $filecontent will go when we fwrite() it.
                        if (!$handle = fopen($fileaddress, ‘a’)) {
                        echo “Cannot open file (“.$fileaddress.”)”;
                        return FALSE;
                         // Write $filecontent which is of array type and stored in $vals to our opened file.
                         if (fwrite($handle, json_encode($query).”\r\n”) === FALSE) {
                        // echo “Cannot write to file ($fileaddress)”;
                         $profiler->add(‘Error Stored in File[‘.$fileaddress.’]’);
                         return TRUE;
                   $profiler->add(‘File [‘.$fileaddress.’] not found.’);
        return FALSE;
 public function readandexecute(){
              return $this->getqueriesfromfile();
      public function getqueriesfromfile(){
                $file = fopen($fileaddress, “r”);
                //Output a line of the file until the end is reached
                    $jsonarray=json_decode($lines, true);
                       // fputs($file, json_encode(array(‘id’=>$jsonarray[‘id’])))
                return $matches;