I need to read a .csv file line by line and assign selected fields to variables.

Posted on 2013-01-10
Last Modified: 2013-01-11
I am currently using .cgi files using Korn Shell (#!/bin/ksh) for file manipulation.
I'm reading a line in at a time and using nawk to send back selected fields and assigning to variables which I plug into my html.  I need to replace the ksh code used in the files with something else such as php and perform the same function.  I experimented with the fgetcsv function and was unable to get it to retrieve the data.  Below is a snippet of the code I'm currently using and would love to get a php alternative that actually works.
The code is using a word/name entered by the user, searching through the file and returning selected fields in the matching record which are assigned variables and displayed in a html table.

     exec 9< $csv
           read -u9 record
                  found=$(echo $record|nawk -F, '{print $0}' | grep -ic "$name" )
                 if [[ $found >0 ]];then
                       lastname=$( echo $record | nawk -F, '{print $2}')
                       firstname=$(  echo $record  | nawk -F, '{print $3}')
                       phone=$(  echo $record  | nawk -F, '{print $10}')
                       if [[ $phone == "" ]];then
                          phone="Not On Record"
                       email=$(  echo $record  | nawk -F, '{print $11}')    
                       if [[ $email == "" ]];then
                          email="Not On Record"
                    print "<td align=\"center\" bgcolor=\"#FFFFFF\"  style=\"border: 5px outset #000060\" >$lastname</td>"
                    print "<td align=\"center\" bgcolor=\"#FFFFFF\"  style=\"border: 5px outset #000060\" >$firstname</td>"
                    print "<td align=\"center\" bgcolor=\"#FFFFFF\"  style=\"border: 5px outset #000060\" >$phone</td>"
                    print "<td align=\"center\" bgcolor=\"#FFFFFF\"  style=\"border: 5px outset #000060\" >$email</td></tr>"                  

exec 9<&-
Question by:dkauger
  • 3
  • 2
LVL 51

Assisted Solution

ahoffmann earned 500 total points
ID: 38766069
$fh=fopen('your.csv','r') or die('**ERR**');
while ($data = fgetcsv($fh,4242,',')) {
   // add your grep match here
    $lastname = $data[2];
    $firstname = $data[3];
    $phone = $data[10];
    $email = $data[11];
  // add your checks for empty values here
    $td  = '<td align="center" bgcolor="#FFFFFF" style="border:5px outset #000060">';
    print "<tr>'.$td . $lastname . '</td>';
    print "$td . $firstname . '</td>';
    print "$td . $phone . '</td>';
    print "$td . $email . '</td></tr>';
// to be improved in many ways

Author Comment

ID: 38767632
I tried plugging the code into my existing file with the test parameters and it crashes with a "Parse error: syntax error, unexpected T_VARIABLE" in the   print "$td . $firstname . '</td>';  line.
Assuming it was due to the surrounding code, I created a test file which also crashed with the following:

Parse error: syntax error, unexpected $end  at the last line of code.  This is my test file:


$fh=fopen('members.csv','r') or die('**ERR**');
while ($data = fgetcsv($fh,4242,',')) {
       $lastname = $data[2];
       $firstname = $data[3];
       $phone = $data[10];
       $email = $data[11];
    $td  = '<td align="center" bgcolor="#FFFFFF" style="border:5px outset #000060">';
    print "<tr>'.$td . $lastname . '</td>';
    print $td . $firstname . '</td>';
    print $td . $phone . '</td>';
    print $td . $email . '</td></tr>';

I assumed that the above code would read each line and print the selected fields.
LVL 51

Expert Comment

ID: 38769056
oops, there is a typo, please replace

    print "<tr>'.$td . $lastname . '</td>';


    print '<tr>'.$td . $lastname . '</td>';
LVL 51

Accepted Solution

ahoffmann earned 500 total points
ID: 38769070
// your grep line looks somehow like (assuming $name proper set):

if(!preg_match('/'.$name.'/i',implode(' ',$data))) { continue; };

Author Comment

ID: 38769310
That did it!  I needed the "preg_match" to do the test for the existence of the searched for word, the grep function only returned "array" in the $data value.  I also needed to shift the array elements by one due to the first field being placed in element 0.
A little practice with this code should solve my search and display problem.

Featured Post

Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
What is assert.deepEqual? 4 59
Debug script powershell wmi 3 20
Need help Creating PowerShell Script 4 47
.dn property wont validate - Powershell 2 23
In this tutorial I will focus on how to use WhizBase as a tool for sending ICQ messages to ICQ. Here I will use a new technology in WhizBase, published in WhizBase 5.1 version. In this tutorial I will use 3 files, pager.wbsp for the processing, e…
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question