Reading and Writing Comma-Separated Data : explode « Data Structure « PHP






Reading and Writing Comma-Separated Data

 
<?php

  $commafile = "data.txt";

  if (file_exists ($commafile)){

    $rows = file ($commafile);
    for ($i = 0; $i < count ($rows); $i++){

      $exprow = explode (",", $rows[$i]);

      echo "ID: " . $exprow[0] . "<br />";
      echo "Name: " . $exprow[1] . "<br />";
      echo "Author: " . $exprow[2] . "<br />";
      echo "<hr />";
    }
  } else {
    echo "File does not exist.";
  }

  $idarray = array ("1","2","3");
  $namearray = array ("Book 1","Book 2","Book 3");
  $authorarray = array ("Author","Author","Author");
    
  $newfile = "data.txt";

  try {
    if ($readfile = fopen ($newfile, "w")){

      for ($i = 0; $i < count ($idarray); $i++){
        $writestring = $idarray[$i] . "," . $namearray[$i] . "," . $authorarray[$i] . "\n";
        fwrite ($readfile, $writestring);
      }
      fclose ($readfile);
    } else {

      throw new exception ("Sorry, the file could not be opened.");
    }
  } catch (exception $e) {
    echo $e->getmessage();
  }
?>
  
  








Related examples in the same category

1.Breaking Strings into Arrays with explode()
2.Display year an individual was born
3.Using the explode() Function
4.Generating an ID with microtime()
5.explode( ) function converts a string into an array using a separator value
6.explode() function divides string into various elements, returning these elements in an array.
7.explode.php
8.Using explode() with date()
9.Processing variable-length text fields