communication
 databases
 directories
 file handling
 html and code
 image editing
 image listing
 sessions and co
 string handling
 information
 forms
 apple stuff
 image handling
 array handling
 lixlpixel
php - snippets
google search terms detected and highlighted.
remove highlighting | keep highlighting
make snippet in "file handling" - download "read and select csv"
 search
php - snippets

Valid CSS!

php webring logo
prev next
random list
join the Ring!

file handling - read and select csv was created/last modified on Mon 12 Apr 2004 6:11 AM

this functions read csv (comma seperated values) files and return the content as an array.
the first one returns the whole file, the second acts like a select statement

perfect for file-based databases

<?php

// reads a csv file and returns a two-dimensional array of lines/fields
function read_csv($file,$delimiter)
{
  
$data_array = file($file);
  for (
$i = 0; $i < count($data_array); $i++ )
  {
   
$parts_array[$i] = explode($delimiter,$data_array[$i]);
  }
  return
$parts_array;
}

// reads a csv file and returns an two-dimensional array of lines/fields
function select_csv($file,$delimiter,$field,$query)
{
  
$data_array = file($file);
  for (
$i = 0; $i < count($data_array); $i++ )
  {
   
$parts_array[$i] = explode($delimiter,$data_array[$i]);
   if(
trim(strtolower($parts_array[$i][$field])) == trim(strtolower($query)))
   {
    
$result_array[] = $parts_array[$i];
   }
  }
  return
$result_array;
}


// ------------------- demonstration below --------------------


// this willl display all records in the csv file
$data = read_csv('read_csv.txt','|');
for (
$i = 0; $i < count($data); $i++ )
{
  for (
$u = 0; $u < count($data[$i]); $u++ )
  {
   echo
$data[$i][$u].' ';
   if(
$data[$i][$u] == end($data[$i]))
   {
    echo
'<br>';  
   }
  }
}


echo
'<p>';  


// this willl display all records where the value
// of the selected field matches the query
$data = select_csv('read_csv.txt','|','1','1069167712');
for (
$i = 0; $i < count($data); $i++ )
{
  for (
$u = 0; $u < count($data[$i]); $u++ )
  {
   echo
$data[$i][$u].' ';
  }
  echo
'<br>';  
}


?>

learn more about some of the PHP functions used in this snippet: array, count, echo, end, explode, file, for, function, ord, return, stat, strtolower, trim

view the GNU general license - view the GNU library license - search on PHPsnippets - see your code like this

 a lixlpixel.com site

PHParadise.com - PHP-classes.org - your site on safari