• 0

[PHP] Read File Lines


Question

Good night to all.
I have this problem:
 

I have this function > 

<?php
function read_items($data_to_read){
if(is_file($data_to_read)){
$file = fopen ($data_to_read, 'r');
while ($current_data_item = fgets($file) !== FALSE){
$item_data_info = fscanf($file, "%d %d %[^\n]s"); 
list($item_primary_key, $item_id, $item_name) = $item_data_info;
if(!empty($item_name) && !empty($item_id)){
echo '<option value="'.$item_id.'">'.$item_id.'</option>';
}
}
fclose($file);
}
}
?>

And i use it like this

<?php read_items('items.txt'); ?>

In Items.txt i have this string lines:

 

1 2621441 Dagger
2 2621442 Scout Dagger
3 2621443 Dirk 
4 2621444 Brave Dirk
5 2621445 Wedge Blade
6 2621446 River Stiletto
7 2621447 Venom Stinger
8 2621448 Onyx Eye Stinger
9 2621449 Blook Dirk
10 2621450 Crystal Gouge

 

And the output is this

http://picbg.net/img.php?file=2664edc757590d52.png

Its shows me 5 items not all (10) -.- dunno why.
Any suggestions... about how to get all lines it skips the 2621441, 2621443, 2621445 etc..

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

the fgets and fscanf function both grab the next line from the filepointer, so fscanf only reads every other line you need to change it to:

 

<?php
function read_items($data_to_read){
    if(is_file($data_to_read)){
        $file = fopen ($data_to_read, 'r');
        while ($item_data_info = fscanf($file, "%d %d %[^\n]s"); !== FALSE){
            list($item_primary_key, $item_id, $item_name) = $item_data_info;
            if(!empty($item_name) && !empty($item_id)){
                echo '<option value="'.$item_id.'">'.$item_id.'</option>';
            }
        }
        fclose($file);
    }
}
?>
Link to comment
Share on other sites

  • 0

 

the fgets and fscanf function both grab the next line from the filepointer, so fscanf only reads every other line you need to change it to:

<?php
function read_items($data_to_read){
    if(is_file($data_to_read)){
        $file = fopen ($data_to_read, 'r');
        while ($item_data_info = fscanf($file, "%d %d %[^\n]s"); !== FALSE){
            list($item_primary_key, $item_id, $item_name) = $item_data_info;
            if(!empty($item_name) && !empty($item_id)){
                echo '<option value="'.$item_id.'">'.$item_id.'</option>';
            }
        }
        fclose($file);
    }
}
?>

Thank you, you helped me alot. Regards 

Link to comment
Share on other sites

This topic is now closed to further replies.