Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and iterate .txt in PHP

Tags:

file

php

I sense that I am almost there. Here is a .txt file, which is about 60 Kbytes and full of German words. Every word is on a new line.

I want to iterate through it with this code:

<?php

    $file = "GermanWords.txt";
    $f = fopen($file,"r");

    $parts = explode("\n", $f);

    foreach ($parts as &$v) 
    {
        echo $v;
    }

?>

When I execute this code, I get: Resourceid#2 The word resource is not in the .txt, I do not know where it comes from.

How can I manage to show up all words in the txt?

like image 752
IMX Avatar asked Sep 30 '12 21:09

IMX


2 Answers

No need for fopen just use file_get_contents:

$file = "GermanWords.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents); // this is your array of words

foreach($lines as $word) {
    echo $word;
}
like image 192
Ahmet Özışık Avatar answered Sep 30 '22 04:09

Ahmet Özışık


fopen() just opens the file, it doesn't read it -- In your code, $f contains a file handle, not the file contents. This is where the word "Resource" comes from; it's PHP's internal name for the file handle.

One answer would be to replace fopen() with file_get_contents(). This opens and reads the file in one action. This would solve the problem, but if the file is big, you probably don't want to read the whole thing into memory in one go.

So I would suggest instead using SplFileObject(). The code would look like this:

<?php
$file = "GermanWords.txt";
$parts = new SplFileObject($file);
foreach ($parts as $line) {
    echo $line;
}
?>

It only reads into memory one line at at time, so you don't have to worry about the size of the file.

Hope that helps.

See the PHP manual for more info: http://php.net/manual/en/splfileobject.construct.php

like image 36
Spudley Avatar answered Sep 30 '22 04:09

Spudley