how to separate and read data from text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
robbydweb
Forum Newbie
Posts: 1
Joined: Mon Dec 13, 2004 11:53 pm

how to separate and read data from text file

Post by robbydweb »

I just started learning php and cant figure this out.
If i have a text file like this:

name1|location1|message1
name2|location2|message2
ect...

How can I read 1 line at a time, separate each section and display each value ? I know how to read a whole text file, but dont know
how to break it up and display each part separaetly.
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

Well if you use fgets() it will just read until the line break, or you can use file() to read the whole file at once, and it places each line in an array item. Then use explode() to get each part seperate.

Code: Select all

$file = "myfile.txt";
$data = file($file);
foreach($data as $line){
   $parts = explode("|", $line);
   print_r($parts);
}
Post Reply