Page 1 of 1

PHP Working with files and tables

Posted: Wed Nov 26, 2008 1:39 pm
by hewstone
Hey,

I have a "exampledata.txt" file contain the following vlaues;

01, Richard, Hewston, 1256,
02, Matt, Mills, 9872,
03, Debbie, Close, 83642,
04, Fred, Wlesh, 1330,
......


I access the file using PHP with the following string;

$fp = fopen("example.txt", "r"); //Reads the file

and read the contains of the file using;
while (!feof($fp)){
$char = fgetc($fp);
echo $char;
}


However this returns all the value in a single line i.e. "01, Richard, Hewston, 1256, 02, Matt, Mills, 9872,......"

How can I get the code to return the values as they are in the "exampledata.txt" file, i.e. when the while loop reaches "/n" (new line) it then echo a new line on screen? (echo "/n";)

Also i want to put these values into a table format or an array? any ideas on how this can be done?

Thanks in advance for you help

Re: PHP Working with files and tables

Posted: Wed Nov 26, 2008 1:41 pm
by hewstone
Also i could use "$line = fgets($fp);" however it is important that i read each character in the file, hence why im using "$char = fgetc($fp);"

Re: PHP Working with files and tables

Posted: Wed Nov 26, 2008 1:43 pm
by hewstone
And further information! - the "exampledata.txt" file contains table table, saparted by the comma - This infor will be useful when discussing how to put the data into tables

Any ideas welcomed!

Re: PHP Working with files and tables

Posted: Wed Nov 26, 2008 1:50 pm
by tamamk

Code: Select all

<?php
 
$fp = fopen("example.txt", "r");
 
while (!feof($fp)){
$char = fgetc($fp);
$array_of_line_values =explode(", ", $char);
 
foreach($array_of_line_values as $key => $value){
    echo $value."<br />";
    if($value == "\n"){
        echo "***********Finished a line*******<br><br>";
        break;
    }
}
 
}
 
?>

Re: PHP Working with files and tables

Posted: Fri Nov 28, 2008 5:50 am
by hewstone
Thank you for the code. Its codes great :D

I now want to but the values in a table or an array. How can this be done? any ideas?

Re: PHP Working with files and tables

Posted: Fri Nov 28, 2008 6:04 am
by tamamk
Look at the code! I named the array "$array_of_line_values". Each line is broken into parts and placed in an array. Google what "explode php" is. Then use the logic that is in that code to do what you want.

If you want to put all values in the same array, you just have to know how to append to an array while using a "while loop" and modify the code above.

Note: "\n" is different than '\n'. "" evaluates things and '' doesn't.