← All Articles A Product of Kinsa Creative

Handling CSV Files in PHP

Getting the Path File

Before being able to parse the file, PHP needs the path to the file to know where it is.

In WordPress

If the file has been uploaded to the media library and the id of the file is available, use the get_attached_file() function to get the path to the file. Before starting to parse the file, make sure it is accessible with the PHP file_exists() function:

<?php
$path_to_file = get_attached_file( $upload_id );

if ( ! file_exists( $path_to_file ) ) {
  return;
}

Parse a CSV File into JSON

<?php
if ( ( $handle = fopen( $path_to_file, 'r' ) ) !== false ) {
  $rows = [];
  while ( ! feof( $handle ) ) {
    $rows[] = fgetcsv( $handle, null, ",", '"' );
  }

  $data         = [];
  $column_names = [];

  // create an array of the column names 
  $column_names = $rows[0];

  // iterate over the rows below the header row
  foreach ( $rows as $key => $row ) {
    // skip the header row
    if ( $key === 0 ) {
      continue;
    }
    foreach ( $column_names as $column_key => $column_name ) {
      $value                            = $row[ $column_key ];
      $value                            = str_replace( ',', '', $value );
      $data[ $key - 1 ][ $column_name ] = $value;
    }
  }
  $json_data = json_encode( $data );
  fclose( $handle );
}

That JSON data can now be passed to JavaScript, for example, by echoing it:

<php echo $json_data; ?>

Parse CSV File into a PHP Associative Array

<?php // Consume the summary data CSV into an array where each row is an associative array with the column names as the keys
if ( ( $handle = fopen( $path_to_file, 'r' ) ) !== false ) {
  $rows = [];
  while ( ! feof( $handle ) ) {
    $rows[] = fgetcsv( $handle, null, ",", '"' );
  }

  $data = [];
  $column_names = $rows[0];

  // iterate over the rows below the header row
  foreach ( $rows as $key => $row ) {
    // Skip the header row
    if ( $key === 0 ) {
      continue;
    }

    $row_data = [];
    foreach ( $column_names as $column_key => $column_name ) {
      $row_data[$column_name] = $row[$column_key];
    }
    $data[] = $row_data;
  }

  fclose( $handle );
}

That data can now be accessed as an associative array:

<?php 
// Iterate over the summary data to find the row for something I want
// For example if the column name is 'Countries', match on the row for 'Spain'
foreach ( $data as $row ) {
  if ( $row['My Column Name'] === 'Value to Match On' ) {
    $data_row_i_want = $row;
    break;
  }
}

// Access the value from a different column in that row
echo $data_row_i_want['Other Column Name']; ?>

Feedback?

Email us at enquiries@kinsa.cc.