Jump to content

fgetcsv function help


sasori

Recommended Posts

im troubled with producing a list of name of my csv file in my browser

 

here is the list in the .csv file

 

Chucky Chucky 12345 Dead St. CA 54321

Freddy Kruger  66666 Elm St. NY 56666

Jason Vorjis 24354 killer St. AK 64524

 

and here's my code

 

<?php

$fh = fopen('../test2/address.csv','r');
$address = fgetcsv($fh,1000);
foreach($address as $name)
{
print_r($name);
}
fclose($fh);

?>

 

it only outputs the first name from the list, in this output on the web browser

 

Chucky Chucky12345Dead St.CA54321

 

Link to comment
https://forums.phpfreaks.com/topic/117911-fgetcsv-function-help/
Share on other sites

from PHP:

fgetcsv — Gets line from file pointer and parse for CSV fields

It only looks at the data, one line per run through.

solution:

<?php
$fh = file("../test2/address.csv");
foreach($fh as $value){
    $data_array = explode("  ", $value);
    $name[] = $data_array[0];
    $address1[] = $data_array[1]." ".$data_array[2];
    $state[] = $data_array[3];
    $zip[] = $data_array[4];
}
print_r($name);
print_r($address);
print_r($state);
print_r($zip);

Can't guarantee syntax. Watching G4 right now, and I'm getting tired.

im troubled with producing a list of name of my csv file in my browser

 

here is the list in the .csv file

 

Chucky Chucky 12345 Dead St. CA 54321

Freddy Kruger  66666 Elm St. NY 56666

Jason Vorjis 24354 killer St. AK 64524

 

 

CSV means "comma separated variables" (although any delimiter character can be used so long as it doesn't appear in the data). So "space", as you have used, is an extremely poor choice as you cannot differentiate between the spaces between the data and the space in, say, "Elm St")

 

Change you data file to

 

[pre]

Chucky Chucky,12345, Dead St.,CA,54321

Freddy Kruger, 66666, Elm St., NY,56666

Jason Vorjis,24354, killer St., AK,64524[/pre]

 

If you use a char other than a comma (default) you have to tell fgetcsv() what char you are using

$fh = fopen('../test2/address.csv','r');
while ($address = fgetcsv ($fh, 1000, "\t"))       // if using a tab char
{
      echo '<pre>', print_r($address, 1), '</pre>';
}
fclose($fh);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.