How to read Specific CSV column data into a PHP variable
I have a CSV file with column headings;
How can I read only the data from col 2 ( the email addresses ) into a variable, without the column headings.
Have you looked at fgetcsv() yet?
There is a class available HERE that you can use to output a specific column to either an array of values, or comma separated string.
Look in the commented out section of the the advanced example for the "$CSV->output_column()" method.
This should make quick work of extracting values from a CSV in any way you want. To extract a column would look like this:
If you do not want to use the class, you can dig in and look at the functions that do the work...I like using the class because there are also built in methods to dump results to a table, XML, JSON, etc... You can also "query" a CSV to extract only certain records, or use the built in forms to edit CSV records.
$data_file = 'my_data_file.txt';
$file_delimiter = '|';
$csv = new csvCRUD($data_file,$file_delimiter);
//To output col B as an array of values:
$col_2_values_array = $csv->output_column('B','array');
//Or to output col B as a comma delim string of values:
$col_2_values_string = $csv->output_column('B','string');
Last edited by hastx; 09-20-2013 at 11:12 AM.
We do precision guesswork
You either look at NogDog's idea of a CSV function, read in the data and you can ignore the first line or...
Assuming that you are parsing the file to insert in to a database, you could do something like...
Thats a rather long winded way of doing it, you can use other methods to get the data you want but from an educational point of view its easier to follow the process.
// split at the new line char
$content = explode("\r\n",file_get_contents("filename.ext"));
// remove the first entry = header
// make a multi-dimentional array
foreach( $content as $entry=>$str )
$content[$entry] = explode(","$str);
// make array to store results
$emails = array();
// put emails in to new array
foreach( $content as $entry )
array_push( $entry );
// house keeping
unset( $content );
Without the comments and the house keeping, its a five line routine.
... and please remember to wrap code with forum BBCode tags:-
[CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]
If you can't think outside the box, you will be trapped forever with no escape...
Somehow, my responses aren't being posted.
I will definitely look into the class.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)