Jump to content

Nesting whiles in ifs


guyfromfl

Recommended Posts

I am writing a script that can handle either csv or xls files.  Once the data is parsed for either type it goes into an array $data  and all the same operations are done on it.

 

Right now, it is only set up to handle a csv file.

 

This is the code I have right now:

 

//Load the CSV files in the UPLOAD_PATH directory
$fileList = $fs->loadFiles(UPLOAD_PATH, "csv");

// Loop through fileList array to processes each file
foreach($fileList as $filename) {
// Attempt to open the next file in the list and process it.
if (($handle = fopen(UPLOAD_PATH.$filename, "r")) != FALSE) {

	// Create the input array
	while(($data = fgetcsv($handle, 0, ",")) != FALSE) {

               // ... do the magic

 

How do I add another set of instructions to goto the parseXLS function that performs basically what fgetcsv does?

 

I think in this case a try...catch statement would be too loose, and wouldnt be the best way.

 

What I would LIKE to do is

 

if (a csv file) {
  while(($data = fgetscv($handle, 0, ",")) != FALSE) {
} else if (an xls file) {
  while ($data = parseXLS()) {
}

// Do the magic
} // end of while

 

I know this won't work but i need to do something along those lines.  Any ideas?

Link to comment
Share on other sites

I'd put the magic in a function and do this:

 

if (a csv file) {
  while(($data = fgetscv($handle, 0, ",")) != FALSE) {
    magic($data);
  }
} else if (an xls file) {
  while ($data = parseXLS()) {
    magic($data);
  }
} else die("unknown type\n");

 

Link to comment
Share on other sites

You could create a file reading class.  The class remembers if it's reading a csv file or an excel file, and has a "next line" method.  You keep calling the next line method until there's no more lines left.  So instead of abstracting out the line processing magic, you've abstracted out the file reading magic.

 

Edit: change "file processing" to "line processing"

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.