Solved

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

Posted on 2004-10-12
8
222 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Expert Comment

by:Gyftus
Comment Utility
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
Comment Utility
Sorry the the  $upLoadDetails does nothing in this case, oops copy and paste mistake
0
 
LVL 27

Expert Comment

by:Diablo84
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 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

11 Experts available now in Live!

Get 1:1 Help Now