Sign in to follow this  

[PHP] Read File Lines

Recommended Posts

xScence    1

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..

Share this post


Link to post
Share on other sites
SinsOfCube    23

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);
    }
}
?>
  • Like 1

Share this post


Link to post
Share on other sites
xScence    1

 

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 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.