Working with text files
Moderator: General Moderators
Working with text files
I have a text file that has been exported from access containing a particular table of data. I wish for the user to enter a job reference and then for them to see the corresponding data from that text file. Is this possible??
Thanks
Dave
Thanks
Dave
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
-
Tubbietoeter
- Forum Contributor
- Posts: 149
- Joined: Fri Mar 14, 2003 2:41 am
- Location: Germany
Trying to read the file into an array
I am sorry if i appear thick, but i am new to php and i am having trouble reading my text file into an array. Can anyone help??
My text file appears like this:
"Id","Name","Number","Address"
1,"Dave","02076547898","9 The grange"
2,"Martin","02065435434","10 Pumton"
Thanks
Dave
My text file appears like this:
"Id","Name","Number","Address"
1,"Dave","02076547898","9 The grange"
2,"Martin","02065435434","10 Pumton"
Thanks
Dave
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
You can use file() and explode(). As an example (based on the structure of your CVS):
Mac
Code: Select all
<?php
$file_contents = file('yourfilename.txt');
foreach ($file_contents as $line_id => $line) {
$line_info = explode(',', $line);
// you'll need to remove the quotes from around the text
foreach ($line_info as $key => $text) {
$text = preg_replace('|^"([^"]+)"$|', '\1', $text);
// check to see if this is not the first line
if ($line_id != 0) {
// create an array indexed by the field names
$text_array[$field_names[$key]] = $text;
} else {
// create an array of the field names
$field_names[] = $text;
}
}
// now you've got an indexed array that you can use to display info
if ($line_id != 0) {
echo <<<END
<h1>Line $line_id</h1>
<h2>Record ID: {$text_array['Id']}</h2>
<ul>
<li><b>Name:</b> {$text_array['Name']}</li>
<li><b>Number:</b> {$text_array['Number']}</li>
<li><b>Address:</b> {$text_array['Address']}</li>
</ul>
END;
}
}
?>- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
Thanks, but....
That worked very well, thanks. However, my database has got bigger and a comments field has been entered. This field has many commas already in it and it appears to be messing up my array. Can you help at all or should i be looking more into how i export my text file??
Thanks
Dave
Thanks
Dave
Searching the array
Also i need to be able to search the array by the ID and show the relevant data. Maybe by finding out which line id the ID is on and printing out that lines data???
Thanks
Dave
Thanks
Dave