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
Mr Tech
Forum Contributor
Posts: 424 Joined: Tue Aug 10, 2004 3:08 am
Post
by Mr Tech » Wed May 28, 2008 11:42 pm
I'm trying to import a CSV file into a website using php but I can't figure it out...First of all my code... which I got from the php.net website...
Code: Select all
$file = 'test.csv';
$fp = fopen($file, 'r');
if (!$fp) {
$err = 1;
}
$length = filesize($file) + 1;
$filecontents = array();
while (($line = fgetcsv($fp, $length, ",")) !== FALSE) {
$filecontents[] = $line;
}
fclose($fp);
The problem is that the whole CSV file is put into the one array instead of breaking each line up into its own array. How do I achieve that?
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Thu May 29, 2008 12:02 am
Each line should be an array. You should end up with an array or arrays. Use print_r() to show the data.
(#10850)
Mr Tech
Forum Contributor
Posts: 424 Joined: Tue Aug 10, 2004 3:08 am
Post
by Mr Tech » Thu May 29, 2008 12:31 am
That's what I thought... however, when it puts it into an array, it doesn't start a sub array when a new line begins... For example... this is how it should look (not sure if I've formatted it correctly but I'm sure you'll get the idea):
Code: Select all
Array
(
Array [0]
(
[0] => Item ID
[1] => Name
)
Array [1]
(
[0] => 1
[1] => Ben
)
Array [2]
(
[0] => 2
[1] => Sarah
)
Array [3]
(
[0] => 3
[1] => Daniel
)
)
This is how it looks with my code:
Code: Select all
Array
(
[0] => Item ID
[1] => Name
[2] => 1
[3] => Ben
[4] => 2
[5] => Sarah
[6] => 3
[7] => Daniel
)