RSS Forums RSS
Please support our PHP advertiser: Lunarpages PHP Web Hosting

Import/export tab delimited file

Join Date: Jun 2005
Location: Kansas City, Missouri, USA
Posts: 345
Reputation: Troy is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 4
Troy's Avatar
Troy Troy is offline Offline
Posting Whiz

Re: Import/export tab delimited file

  #5  
Jun 9th, 2005
First, you said you had the import working, but you ended up with double quotes in your values. You can strip those using code like:
[php]
$val = str_replace('"', '', $val);
[/php]

Here is example code that shows you how to connect to a mysql server, select a specific database, execute a SQL statement, then work with the data.
[php]
<?php

$server = "localhost"; // Name or IP of database server.
$user = ""; // username
$pwd = ""; // password
$db = ""; // Name of database to connect to.

if (!$cnn = mysql_connect($server,$user,$pwd )) {
die("mysql_connect() failed");
}

if (!mysql_select_db($db,$cnn)) {
die("Could not select database named ".$db);
}

/* Build your SQL statement however you need. */
$sql = "select * from mytable";

/* Execute the query. */
if (!$res = @mysql_query($sql)) {
die(mysql_error());
return false;
}
/* Create an array of arrays out of the recordset. */
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$data[] = $row;
}

/* Now iterate through the recordset creating a simple table. */
echo "<style>table.dump { font-family:Arial; font-size:8pt; }</style>";
echo "<table class=\"dump\" border=\"1\" cellpadding=\"1\" cellspacing=\"0\">\n";
echo "<tr>";
echo "<th>#</th>";
foreach($data[0] as $key=>$val) {
echo "<th><b>";
echo $key;
echo "</b></th>";
}
echo "</tr>\n";
$row_cnt = 0;
foreach($data as $row) {
$row_cnt++;
echo "<tr align='center'>";
echo "<td>".$row_cnt."</td>";
foreach($row as $val) {
echo "<td>";
echo $val;
echo "</td>";
}
echo"</tr>\n";
}
echo "</table>\n";

?>
[/php]

Next, you need to know how to save the recordset back into a TAB delimited file. This example uses the $data value from the code example above.
[php]
<?php
$fp = fopen("path_to_file_here", "w");

foreach($data as $row) {

$line = "";

foreach($row as $val) {
$line .= "\t\"".$val."\"";
}

/* Strip off the first TAB and add a carriage return. */
$line = substr($line, 1)."\n";

$fwrite($line);
}

fclose($fp);

?>
[/php]

I hope that helps! Enjoy the journey!
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 10:57 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC