Solved

How do i parse a text file with fields seperated by tabs?

Posted on 2004-10-12
8
225 Views
Last Modified: 2008-02-07
Hi.. I've got a tab-delimited text file that came exported out of a mysql database.

I want to feed these fields into another database but I need a way to input the seperate fields into different fields.

Only way i can come up with is using perl or cgi to split the line into array variables, using the tabs as seperators.

However, I'm at somewhat of a loss as to how to do this.
(I know a little more perl then i do php sadly)

Any ideas on how to do this in php please?

I've used stuff like:

$var=time();
$entrydate=date('d/m/Y',$var);

$explode = explode ('/', $entrydate);
$daydate=$explode[0];
$monthdate=$explode[1];
$yeardate=$explode[2];

to split the line up before but I've got no idea what the ascii code for a tab is?

thanks

Daryn
0
Comment
Question by:daryn
  • 4
  • 2
8 Comments
 
LVL 27

Accepted Solution

by:
Diablo84 earned 300 total points
ID: 12289181
For tabs you will be wanting to use \t in a similar way that \n is used for new lines

$var = explode("\t",$yourstring);
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12289268
If the data is seperated by new lines and tabs, eg:

value1    value2    value 3    value4
value1    value2    value 3    value4
value1    value2    value 3    value4

you might first want to explode the file contents by \n to get each line into an array item

and then explode each of these items by \t to get the induvidual values

example:

$var = file_get_contents($_SERVER['DOCUMENT_ROOT']."/path/to/your/file.txt");

$phase1 = explode("\n",$var);

foreach ($phase1 as $var) {
 $phase2[] = explode("\t",$var);
}

You then have a 2 dimensional array assigned to $phase2:

you can view its contents using:

echo "<pre>";
print_r($phase2);
echo "</pre>";

or induvidual items can be accessed like this, if for example the first line in the file was
value1    value2    value 3    value4

echo $phase2[0][0]; //would output value1

0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12289382
To extend on that, you could also work the database inserting like this:

//DATABASE CONNECTION STRING

$var = file_get_contents($_SERVER['DOCUMENT_ROOT']."/path/to/your/file.txt");

$phase1 = explode("\n",$var);

foreach ($phase1 as $var) {
 $phase2 = explode("\t",$var);
 for ($i=0;$i<count($phase2);$i++) $phase2[$i] = "'".$phase2[$i]."'";
 $phase2 = implode(",",$phase2);
 $query = mysql_query("INSERT INTO tablename (field1,field2,field3,etc) VALUES ($phase2)") or die(mysql_error());
}

Untested. For a more specific example i would need to see an exact example of the files format but hopefully theres enough information here so you can work it out.


0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Expert Comment

by:Gyftus
ID: 12290104
The same exact solution as the one above, the only difference is that I have already tested it, you can change your fields accordingly, for the insertion in the database of you choice

            $myFile =  file_get_contents(//your file here//);
            $myFile = split("\r\n",$myFile);
            $myFileSize = sizeof($myFile);

            $upLoadDetails;

            
            for($i=0; $i<$myFileSize-1; $i++){
                  
                  
                  $tempD = split("\t",$myFile[$i]);
                  
                  $date = split("/",$tempD[0]);
                  $myDetails['date']            = mktime(0,0,0,$date[1],$date[0],$date[2]);
                  $myDetails['ax']            = addslashes($tempD[1]);
                  $myDetails['para']            = addslashes($tempD[2]);
                  $myDetails['client']      = addslashes($tempD[3]);
                  $myDetails['code']            = addslashes($tempD[4]);
                  $myDetails['item']            = addslashes($tempD[5]);
                  $myDetails['cx1']            = addslashes($tempD[6]);
                  $myDetails['cx2']            = addslashes($tempD[7]);
                  $myDetails['sup']            = addslashes($tempD[8]);
                  $myDetails['amount']      = addslashes($tempD[9]);
                  $myDetails['stock']            = addslashes($tempD[10]);

                  

            
                  

                  $query = "INSERT INTO info VALUES('{$i}',
                                                                        '{$myDetails['date']}',
                                                                        '{$myDetails['ax']}',
                                                                        '{$myDetails['para']}',
                                                                        '{$myDetails['client']}',
                                                                        '{$myDetails['code']}',
                                                                        '{$myDetails['item']}',
                                                                        '{$myDetails['cx1']}',
                                                                        '{$myDetails['cx2']}',
                                                                        '{$myDetails['sup']}',
                                                                        '{$myDetails['amount']}',
                                                                        '{$myDetails['stock']}')";
                  
                  mysql_query($query,$link) or die("Error :".mysql_error($link));

            }

Also if you know for a fact that your file lines ARE separated by \n only you can use the file() command which reads the file into an array, each position representing a line

Cheers
0
 

Expert Comment

by:Gyftus
ID: 12290140
Sorry the the  $upLoadDetails does nothing in this case, oops copy and paste mistake
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12290195
Gyftus, please do not reiterate examples that have already been given, if you want to expand on comments or provide alternative solutions then that is one thing, but posting a solution based upon the exact same methods as already explained by another user is not necessary. Thank you.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

911 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

18 Experts available now in Live!

Get 1:1 Help Now