Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6650339
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T00:52:52+00:00 2026-05-26T00:52:52+00:00

There are a few ways to read CSV files with PHP. I used to

  • 0

There are a few ways to read CSV files with PHP. I used to use the explode function to put each line into an array and then explode commas and use trim to remove any quotation marks from around the data. It was messy…

In PHP 5 there’s now fgetcsv and *str_getcsv*… I’m guessing this is the best way to go about it these days so I’ve whipped together some code…

$fp = fopen($csv_file['file_path'], 'r');       
while (($data = fgetcsv($fp, 0, "\r", '"', "\r")) !== FALSE) {
    $num = count($data);
    for ($c=0; $c < $num; $c++) {
        print_r(str_getcsv($data[$c]));
    }
}

It seems to work but is there a more fail safe approach? For example making it work whether line breaks are \n or \r…

Any input you can give would be awesome!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T00:52:52+00:00Added an answer on May 26, 2026 at 12:52 am

    This converts the CSV into a nested array. Might be easier for you to deal with:

    <?php
        /**
         * 
         */
        function csv_entry_to_array(array $row)
        {
            $column_count = count($row);
            $csv_column_values = array();
    
            // Loop through the columns of the current CSV entry and store its value
            for ($column_index = 0; $column_index < $column_count; $column_index++)
            {
                // Store the value of the current CSV entry
                $csv_column_values[] = $row[$column_index];
            }
    
            // Return
            return $csv_column_values;      
        }
    
        /**
         * @param string    $input_file_name            Filename of input CSV
         * @param boolean   $include_header_in_output   Flag indicating whether the first entry in the CSV is included in the output or not.
         * @param integer   $length                     Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters).
         *                                              It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is
         *                                              not limited, which is slightly slower.
         * @param string    $delimeter                  Set the field delimiter (one character only).
         * @param string    $enclosure                  Set the field enclosure character (one character only).
         * @param string    $escape                     Set the escape character (one character only). Defaults as a backslash.
         * $return  array                               Nested indexed array representing the CSV. Empty array on error (e.g. input file missing, input file not a CSV).
         */
        function csv_file_to_array($input_file_name, $include_header_in_output = TRUE, $length = 1000, $delimeter = ',', $enclosure = '"', $escape = '\\')
        {
            // NOTE: this attempts to properly recognize line endings when reading files from Mac; has small performance penalty
            ini_set('auto_detect_line_endings', TRUE);
    
            $csv_array = array();
    
            // Warnings are supressed, but that's OK since the code handles such warnings
            if (($handle = @fopen($input_file_name, "r")) !== FALSE)
            {
                $row_counter      = 0;
    
                // Iterate over the CSV entries
                while (($row = fgetcsv($handle, $length, $delimeter, $enclosure, $escape)) !== FALSE)
                {           
                    if ($row_counter === 0 && $include_header_in_output === TRUE)
                    {
                        // This is the first row in the CSV and it should be included in the output
                        $csv_array[] = csv_entry_to_array($row);                
                    }
                    else if ($row_counter > 0)
                    {
                        // This is a row in the CSV that needs to be stored in the return array
                        $csv_array[] = csv_entry_to_array($row);
                    }
    
                    $row_counter++;
                }
    
                // Close file handler
                fclose($handle);
            }
            else
            {
                // Input file: some error occured
                return array();
            }
    
            return $csv_array;
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

There are a few ways to get class-like behavior in javascript, the most common
There are a few ways that I'm testing my ray-box intersections: Using the ComputeIntersectionBox(...)
I know how to use locks in my app, but there still few things
There are a few things that I almost always do when I put a
I have read there are a few flags in gcc to do catch some
It looks like there a few working solutions for using custom true type fonts
There are a few books about specific ORM products such as Hibernate or Linq
There are a few questions on SO already regarding LINQ pivots and while a
There are a few questions about configuring Apache for local development, such as this
There are a few APIs for grabbing the address book/contact list from the major

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.