Differences

This shows you the differences between two versions of the page.

Link to this comparison view

using_php_on_csv_files [2015/08/26 14:03]
Joel Dare
using_php_on_csv_files [2020/06/01 22:53]
Line 1: Line 1:
-===== Using PHP on CSV Files ===== 
  
-You can use PHP to quickly get a column of data from a CSV file. Here's an example CSV format. 
- 
-    "​John",​ "​Doe",​ "​801-555-5555"​ 
- 
-PHP has the function fgetcsv() which is great for grabbing data from a CSV file. 
- 
-Here's an example script where I loop through a CSV file grabbing the 3rd column of information. 
- 
-<​code>​ 
-<?php 
- 
-// File and column 
-$file = '​myfile.csv';​ 
-$column = 3; 
- 
-// Subtract one from the column because fgetcsv is zero based 
-$column = $column - 1; 
- 
-// Open the file for reading 
-if (($handle = fopen($file,​ "​r"​)) === FALSE) { 
-    echo "​Couldn'​t open file.";​ 
-} 
- 
-// Loop through the file one CSV line at a time 
-while (($data = fgetcsv($handle,​ 1000, ","​)) !== FALSE) { 
-    // Output the specified column for this line 
-    echo $data[$column] . "​\n";​ 
-} 
- 
-// Close the file 
-fclose($handle);​ 
-</​code>​ 
- 
-To use that script, simply change the $file value to the file you want to open and the $column value to the column number you want to extract. Save the file as getcol.php and then run it with the following command. 
- 
-    php getcol.php 
- 
-The script above only uses memory for one line at a time. As a result, the number of lines it can process is almost unlimited. This is great if you're trying to use a Excel to process a file and getting the "too many rows" error message. 
- 
-The fgetcsv() function is also very good at parsing quoted data correctly. 
- 
-<​html>​ 
-<a id="​csv_link"​ href="​https://​www.paypal.com/​cgi-bin/​webscr?​cmd=_s-xclick&​hosted_button_id=SNV2TUB7Q3PKN">​ 
-<img id="​csv_submission"​ src="​https://​dl.dropboxusercontent.com/​u/​58852318/​ads/​csv_submission/​csv_subscription_a.png">​ 
-</a> 
-</​html>​ 
comments powered by Disqus
using_php_on_csv_files.txt · Last modified: 2020/06/01 22:53 (external edit)