1

I have a giant list in excel, they are just two columns

name    type

The file is currently being read:

$lines = array_map('str_getcsv', file('file.csv', FILE_IGNORE_NEW_LINES));

print_r($lines); returns:

   name1;type
   name2;type2
   ...

Array ( [0] => Array ( [0] => name1;type1) [1] => Array ( [0] => name2;type2)...

I would like to access separate name and type in an foreach

How can I do this? Thanks

2 Answers 2

2

str_getcsv default delimiter is ',' so you need call it somehow with explicitly specifying ';' as delimeter

for example like this

$myGetCsv = function ($str) {
    return str_getcsv($str, ';');
};

$lines = array_map($myGetCsv, file('file.csv', FILE_IGNORE_NEW_LINES));
Sign up to request clarification or add additional context in comments.

Comments

0

Use this code for CSV file reading. it ease to use and understand how its work.

if (($handle = fopen('./suppression_invalid_emails.csv', "r")) !== false) {
     //getting column name
     $column_headers = fgetcsv($handle);
     foreach ($column_headers as $header) {
        //column as array;
          $result[$header] = array();
     }
     // get data for column;
     while (($data = fgetcsv($handle)) !== false) {
          $i = 0;
          foreach ($result as &$column) {
               $column[] = $data[$i++];
          }
     }
     fclose($handle);
    echo '<pre>'; print_r($result); echo '</pre>';
}

i use two basic function for this 1st one is fopen for reading file and other is fgetcsv for getting data for column.

and result is:

Array
(
    [reason] => Array
        (
            [0] => Mail domain mentioned in email address is unknown
            [1] => Known bad domain
            [2] => Known bad domain
        )

    [email] => Array
        (
            [0] => [email protected]
            [1] => [email protected]
            [2] => [email protected]
        )

    [created] => Array
        (
            [0] => 1502644294
            [1] => 1502480171
            [2] => 1502344320
        )

)

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.