getaway
getaway

Reputation: 8990

accessing text files using php?

i was wondering how i can use php to access text files and display the information using php arrays, this might seem like a newbie question, but i havent worked with external files.

so here goes.

home.txt:

ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5

what i wanted to do is sort this information in a html table, with each line as a row and 4 coloumns to represent the data!! thanks cheers :))

Upvotes: 1

Views: 187

Answers (4)

Guerilla
Guerilla

Reputation: 80

you should look at the file() function too, it reads the file into an array line by line.
after that you can seperate the values with explode().

<?php
  $foo = file('example.txt');
  // will echo the 2nd line of the example.txt-file
  echo $foo[1];
  // echos all items seperated by a comma
  foreach($foo as $line=>$values){
    $value_arr = explode(',',$values);
    echo 'line #'.$line.': ';
    foreach($value_arr as $id=>$item){
      echo $id.': '.$item.'; ';
    }
    echo "\n";
  }
?>

Upvotes: 1

Service Informatique
Service Informatique

Reputation: 178

you can do something like that :

<?php
$file = file_get_content('file.txt');

$array = explode("\n", $file);

Notice that it depend of your newline type :

typically:

  • Gnu/Linux / Unix / MacOS since X use "\n"
  • Windows use "\r\n"
  • MacOS before X use "\r"

Upvotes: 3

Haim Evgi
Haim Evgi

Reputation: 125466

a start of deal with this :

  # echo before table headline
    ...........
    $handle = @fopen("myfile.txt","r");
    # read line by line
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo '<tr>';
            $array = explode(',', $buffer);
        foreach($array as $val){
             echo '<td>'.$val.'</td>';      
            } 
        echo '</tr>';       
    }

Upvotes: 0

toomasr
toomasr

Reputation: 4781

Looks like comma separated values. See the examples at http://ee.php.net/manual/en/function.fgetcsv.php

Upvotes: 8

Related Questions