0

I have a CSV file and I want to parse it using PHP:

Access_Code,Home_Address, Work_Address

1, 100 Broad St, 100 Main St

2, 200 Broad St, 200 Main St

3, 300 Broad St, 300 Main St

Here is my code:

$file = fopen($target_path,"r");
while(!feof($file))
{
$groups2 = fgetcsv($file,",");
print_r($groups2);
}
fclose($file);

I don't want anything fancy, just to figure out why this happens:

OUTPUT:

Array ( [0] => Access_Code [1] => Work_Address [2] => Home_Address 1 [3] => 100 Broad St [4] => 100 Main St 2 [5] => 200 Broad St [6] => 200 Main St 3 [7] => 300 Broad St [8] => 300 Main St )

I should have an array with 12 objects, no? Why is my first column being swallowed up by the third (i.e. Home_Address 1, 200 Main St 3, etc.)?

Thanks!!

2
  • 5
    You should have 4 seperate arrays... Your end-of-line character is off (is it perhaps MAC related & \r instead of \n?), find out what it is, and maybe use auto_detect_line_endings Commented Dec 5, 2013 at 22:07
  • I agree, it looks like all his data is on a single line. Hence why the access_code is always part of the preceeding work_address Commented Dec 5, 2013 at 22:27

2 Answers 2

2

I inputted your sample data and code and it returned the following array. Check your data is really in this format. If it is, use file() to read into an array and check the eol characters since file() retains the eol character (see below for code).

Array ( [0] => Access_Code [1] => Home_Address [2] => Work_Address ) 
Array ( [0] => 1 [1] => 100 Broad St [2] => 100 Main St ) 
Array ( [0] => 2 [1] => 200 Broad St [2] => 200 Main St ) 
Array ( [0] => 3 [1] => 300 Broad St [2] => 300 Main St )

Data:

Access_Code,Home_Address, Work_Address
1, 100 Broad St, 100 Main St
2, 200 Broad St, 200 Main St
3, 300 Broad St, 300 Main St

Check eol characters:

$a = file("../x.txt");
$hex='';
for ($i=0; $i < strlen($a[0]); $i++)
{
    var_dump(ord($a[0][$i]));
}
Sign up to request clarification or add additional context in comments.

Comments

2

As wrikken mentioned in the comments, and suggested/linked to.

Your line-endings are wrong.

Line endings are usually done by carriage returns + new line \r\n (windows) , just carriage return \r (mac) or just new line \n (linux/unix).

Try using ini_set("auto_detect_line_endings", true); at the top of your PHP, as suggested in Wrikken's link to the PHP manual on this item.

If this doesn't solve it, check if the delimiter (usually a line ending) is being set correctly, there where you create the CSV file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.