Browsing: PHP CSV Parser Class

This class can be used to parse and display data from a CSV file. It can open and parse the lines of a given CSV file. The data is stored in an array class variable.

It is an ideal class to read CSV files. This script will allow you to read CSV files very easily and efficiently using PHP.

Features

  • PHP CSV Parser Class can “Read” CSV files
  • PHP CSV Parser Class can “Write” CSV files
  • Efficient CSV file parsing by using PHP built-in method
  • Flexible option to use CSV delimiter
  • Number of CSV fields are integrated in the class
  • Reading CSV heading options

Requirements

  • PHP5 or higher

Learning and handling of PHP CSV Parser Class by TutorialChip is very easy and flexible. I have also given a complete demo and usage in the download archive for your understanding, and i am going to explain the installation of this class step by step online as well.

Here is the installation and utilization guide of PHP CSV Parser class for “reading” and “writing” CSV files.

PHP CSV Parser Class: Reading Mode

Here is step by step tutorial to understand the reading mode of PHP CSV Parser class.

Include “class.chip_csv.php”

You have to include chip CSV class in your file at the suitable position you think. Availability of CSV file is the best location in your script.

/*
|-----------------
| Include Chip CSV Class
|------------------
*/
require_once("class.chip_csv.php");

Class Instance

It is time to instance PHP CSV Parser class now,

/*
|-----------------
| Chip CSV Class Instance
|------------------
*/

$object_csv = new Chip_csv();

Array: $args

  • csv_file (String – Absolute Path): It will hold absolute path of CSV file.
  • csv_delimiter (String – Valid Delimiter of CSV file): It can be “,” or “;” or a delimiter that is suitable to your CSV file.
  • csv_fields_num (boolean TRUE | FALSE): PHP CSV Parser Class can detect the number of fields of a row in the CSV file. You can switch on or off this variable to include or exclude number of fields information in the output array
  • csv_head_read (boolean TRUE | FALSE): Heading remains in the most CSV file in the first row. Chip CSV Parser Class give you powerful option to include or exclude CSV heading in the output array.
  • csv_head_label (boolean TRUE | FALSE): You can label CSV parsed data optionally, provided you have made csv_head_read TRUE

Read CSV File

It is time to send command to the Chip CSV Parser Class to read CSV file. Code snippet is,

/*
|---------------------------
| CSV Inputs
|---------------------------
*/

$args = array (
	'csv_file'			=>	$val['uploaded_directory'],
	'csv_delimiter'		=>	$_POST['delimiter'],
	'csv_fields_num'	        =>	TRUE,
	'csv_head_read'		=>	TRUE,
	'csv_head_label'	        =>	TRUE,
);

$csv_output = $object_csv->get_read( $args );

csv_output Anatomy: All Options Enabled

I have taken sample output of $csv_output variable after making all options enabled. Let’s have a look,

Array
(
    [csv_file_read] => 1
    [csv_file_read_status] => CSV File Read Successfully
    [csv_file] => E:\wamp\www\tutorialchip\chip_csv_parser\1.0/uploads/fruits.csv
    [csv_file_data] => Array
        (
            [1] => Array
                (
                    [0] => Name
                    [1] => Code
                    [2] => Price
                )

            [2] => Array
                (
                    [0] => Apple
                    [1] => 1001
                    [2] => $1
                )

            [3] => Array
                (
                    [0] => Orange
                    [1] => 1002
                    [2] => $2
                )

            [4] => Array
                (
                    [0] => Banana
                    [1] => 1003
                    [2] => $0.50
                )

            [5] => Array
                (
                    [0] => Grapes
                    [1] => 1004
                    [2] => $5
                )

        )

)

Output Analysis

  • csv_file_read (boolean TRUE | FALSE): This variable gives you a powerful information about the status of CSV file reading. It will be TRUE in case of successful reading and vice-versa.
  • csv_file_read_status (string – Process Flag): It gives you CSV Parser Class feedback in the human readable format
  • csv_file (string CSV File Path): It gives you information about the processed CSV file path
  • csv_file_data (array CSV File Data): This variable holds CSV data after successful parsing the file.

Complete Tutorial – PHP CSV Parser Class Example

I have already explained the usage of PHP CSV Parser class in steps. Now it is time to see the whole tutorial at once. I have used PHP Upload Class of TutorialChip to use the power of flexible and professional coding.

I will recommend to see details and download Chip PHP Upload Class, this can be very helpful for your CSV Parser and other projects relating to PHP.

/*
|-----------------
| POST
|------------------
*/

if( $_POST ) {

	/*
	|-----------------
	| Chip Upload Class
	|------------------
	*/

	require_once("class.chip_upload.php");

	/*
	|-----------------
	| Upload(s) Directory
	|------------------
	*/

	$upload_directory = CHIP_DEMO_FSROOT . "uploads/";

	/*
	|-----------------
	| Class Instance
	|------------------
	*/

	$object = new chip_upload();

	/*
	|-----------------
	| $_FILES Manipulation
	|------------------
	*/

	$files = $object->get_upload_var( $_FILES['upload_file'] );
	//$object->chip_print( $files );

	/*
	|-----------------
	| Upload Output Array
	|------------------
	*/

	$upload_output = array();

	/*
	|-----------------
	| Upload File
	|------------------
	*/

	foreach( $files as $file ) {

		/*
		|---------------------------
		| Upload Inputs
		|---------------------------
		*/

		$args = array(
			  'upload_file'			=>	$file,
			  'upload_directory'	=>	$upload_directory,
			  'allowed_size'		=>	512000,
			  'extension_check'		=>	TRUE,
			  'upload_overwrite'	=>	FALSE,
		  );

		$allowed_extensions = array (

			  /* Archives */
			  'zip'		=> FALSE,
			  '7z'		=> FALSE,

			  /* Documents */
			  'csv'		=> TRUE,
			  'txt'		=> FALSE,
			  'pdf'		=> FALSE,
			  'doc' 	=> FALSE,
			  'xls'		=> FALSE,
			  'ppt'		=> FALSE,

			  /* Executables */
			  'exe'		=> FALSE,

			  /* Images */
			  'gif'		=> FALSE,
			  'png'		=> FALSE,
			  'jpg'		=> FALSE,
			  'jpeg'	=> FALSE,

			  /* Audio */
			  'mp3'		=> FALSE,
			  'wav'		=> FALSE,

			  /* Video */
			  'mpeg'	=> FALSE,
			  'mpg'		=> FALSE,
			  'mpe'		=> FALSE,
			  'mov'		=> FALSE,
			  'avi'		=> FALSE

		  );

		/*
		|---------------------------
		| Upload Hook
		|---------------------------
		*/		

		$upload_hook = $object->get_upload( $args, $allowed_extensions );
		#$object->chip_print( $upload_hook );
		#exit;

		/*
		|---------------------------
		| Move File
		|---------------------------
		*/

		if( $upload_hook['upload_move'] == TRUE ) {

			/*
			|---------------------------
			| Any Logic by User
			|---------------------------
			*/

			/*
			|---------------------------
			| Move File
			|---------------------------
			*/

			$upload_output[] = $object->get_upload_move();
			//$object->chip_print( $upload_output );

		} else {

			/*$temp['uploaded_status'] = FALSE;
			$temp['uploaded_file'] = $upload_hook['upload_file']['name'] ;

			$upload_output[] = $temp;*/

		}

	} // foreach( $files as $file )

	/*
	|-----------------
	| Chip CSV Class
	|------------------
	*/

	require_once("class.chip_csv.php");
	$object_csv = new Chip_csv();

	/*
	|---------------------------
	| Read CSV File
	|---------------------------
	*/

	if( count( $upload_output ) >= 1 ) {

		foreach ( $upload_output as $val ) {

			if( $val['uploaded_status'] == 1 ) {

				/*
				|---------------------------
				| CSV Inputs
				|---------------------------
				*/

				$args = array (
						'csv_file'			=>	$val['uploaded_directory'],
						'csv_delimiter'		=>	$_POST['delimiter'],
						'csv_fields_num'	=>	FALSE,
						'csv_head_read'		=>	TRUE,
						'csv_head_label'	=>	FALSE,
					);

				$csv_output = $object_csv->get_read( $args );
				//$object_csv->chip_print( $csv_output );

			}

		} // foreach ( $upload_output as $val )

	} // if( count( $upload_output ) >= 1 )	

} // if( $_POST )

PHP CSV Parser Class: Writing Mode

This PHP CSV Parser Class can write CSV files efficiently. I am going to explain CSV Parser Class in “writing” mode as simple as possible.

Include “class.chip_csv.php”

It is essential step to include CSV Parser class, before using its power.

/*
|-----------------
| Chip CSV Class
|------------------
*/

require_once("class.chip_csv.php");
$object = new Chip_csv();

PHP Array to Write CSV File

Here is the format of PHP array which is compatible with PHP CSV Parser class.

/*
|---------------------------
| PHP Array to write in CSV file
|---------------------------
*/

$csv_write_array = array(
	0	=>	array( "Name", "Code", "Price" ),
	1	=>	array( "Apple", "1001", "$1" ),
	2	=>	array( "Orange", "1002", "$2" ),
	3	=>	array( "Banana", "1003", "$0.50" ),
	4	=>	array( "Grapes", "1004", "$5" ),
);

Write CSV File

It is time to use the power of PHP CSV Parser class for writing CSV file.

/*
|---------------------------
| CSV File to Write
|---------------------------
*/

$csv_file = CHIP_DEMO_FSROOT . "write/fruits.csv";

/*
|---------------------------
| CSV Inputs
|---------------------------
*/

$args = array (
		'csv_file'			=>	$csv_file,
		'csv_delimiter'		=>	",",
		'csv_write_array'	=>	$csv_write_array,
	);

$csv_output = $object->get_write( $args );

Complete Tutorial – PHP CSV Parser Class Example Writing Mode

/*
|-----------------
| Chip CSV Class
|------------------
*/

require_once("class.chip_csv.php");
$object = new Chip_csv();

/*
|---------------------------
| PHP Array to write in CSV file
|---------------------------
*/

$csv_write_array = array(
	0	=>	array( "Name", "Code", "Price" ),
	1	=>	array( "Apple", "1001", "$1" ),
	2	=>	array( "Orange", "1002", "$2" ),
	3	=>	array( "Banana", "1003", "$0.50" ),
	4	=>	array( "Grapes", "1004", "$5" ),
);

/*
|---------------------------
| CSV File to Write
|---------------------------
*/

$csv_file = CHIP_DEMO_FSROOT . "write/fruits.csv";

/*
|---------------------------
| CSV Inputs
|---------------------------
*/

$args = array (
		'csv_file'			=>	$csv_file,
		'csv_delimiter'		=>	",",
		'csv_write_array'	=>	$csv_write_array,
	);

$csv_output = $object->get_write( $args );
//$object->chip_print( $csv_output );

Screenshot

PHP CSV Parser Class

Online Demo

I have developed online demo of this PHP CSV Parser Class. I hope you will enjoy.

Download Package – 9.02 Kb

Click here to download complete package of this script. Package will contain,

  • class.chip_csv – Main PHP CSV Parser Class
  • class.chip_upload – Helping PHP Upload Class by TutorialChip
  • index.php – Demo home page
  • style.css – Minimal style
  • write.php – PHP CSV Parser demo to write CSV file
  • samples – Directory containing samples for testing this class
  • uploads – Directory where the files will be stored after uploading
  • write – Directory where the files will be stored after CSV writing

1.0

PHP CSV Parser class is released on January 10, 2011.

  • This is the first version of Chip PHP CSV Parser Class.
email