faqts : Computers : Programming : Languages : PHP

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

14 of 22 people (64%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

how to input data from txt file into table where columns are separated with pipe ?

Apr 22nd, 2008 22:39
dman, Edwin Chan, Philip Olson, Lee Forkenbrock, Kakadu Slash, http://www.ttnr.org


Assuming you have text such as:
  a|b|c
  d|e|f
  g|h|i
First, open the file with file() which will make each line an element 
of
an an array, so:
  $lines = file('somefile.txt');
Now, let's loop through it and create our HTML table, the following is
one such way:
<table>
<?php
  foreach ($lines as $line) {
      list($a, $b, $c) = explode('|', $line);
          print "<tr>
                   <td>$a</td>
                   <td>$b</td>
                   <td>$c</td>
                 </tr>";
      } 
  }
?>
</table>
The key function here is explode(), see:
  http://www.php.net/explode
For a more detailed faqt on how/why this works, see:
  http://www.faqts.com/knowledge_base/view.phtml/aid/7212
If you are meaning MySQL, then the following will help:
  LOAD DATA INFILE "somefile.txt" 
  INTO TABLE table_name 
  FIELDS TERMINATED BY '|';
This should make the pipe be the delimeter for each field read in. 
Refer to mysql.com for more information on LOAD DATA INFILE and its 
attributes.