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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

If you get a (Blue Screen of Death), your system writes a small file called a minidump. Your first step is to make certain your computer is setup to record memory dumps. Right click My Computer, choose properties. Click on the advanced tab, an…
This article will show, step by step, how to integrate R code into a R Sweave document
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now