开发者

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,开发者_JS百科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 :))


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


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"


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";
  }
?>


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>';       
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜