Convert CSV to PHP

Every once in a while, I have a static list of values that I don't want to put into a database, but that I do want to use in my PHP application. That static data can come from a variety of sources, but often it's in a spreadsheet. This handy hack converts any CSV data (one of the easiest formats to pull from a spreadsheet) to PHP code that I can then copy and paste into my PHP page.
<html>
<body>
<form method="post" action="commaconv.php" />
<table>
<tr><td>CSV Data:</td>
<td><textarea name="data" cols="40" rows="10">
"Alabama",4530182
"Alaska",655435
"Arizona",5743834
"Arkansas",2752629
"California",35893799
"Colorado",4601403
"Connecticut",3503604 
"Delaware",830364 
"District of Columbia",553523 
"Florida",17397161 
"Georgia",8829383 
"Hawaii",1262840 
"Idaho",1393262 
"Illinois",12713634 
"Indiana",6237569

"Iowa",2954451
"Kansas",2735502 
"Kentucky",4145922 
"Louisiana",4515770 
"Maine",1317253 
"Maryland",5558058 
"Massachusetts",6416505 
"Michigan",10112620 
"Minnesota",5100958 
"Mississippi",2902966 
"Missouri",5754618 
"Montana",926865 
"Nebraska",1747214 
"Nevada",2334771 
"New Hampshire",1299500 
"New Jersey",8698879 
"New Mexico",1903289 
"New York",19227088 
"North Carolina",8541221 
"North Dakota",634366 
"Ohio",11459011 
"Oklahoma",3523553 
"Oregon",3594586 
"Pennsylvania",12406292 
"Rhode Island",1080632 
"South Carolina",4198068 
"South Dakota",770883 
"Tennessee",5900962 
"Texas",22490022 
"Utah",2389039 
"Vermont",621394 
"Virginia",7459827 
"Washington",6203788 
"West Virginia",1815354 
"Wisconsin",5509026 
"Wyoming",506529</textarea></td></tr>
<tr><td> Field Name 1:</td><td><input name="field0" value="state" /></td></tr>
<tr><td> Field Name 2:</td><td><input name="field1" value="population" /></td>
		  </tr>
<tr><td> Field Name 3:</td><td><input name="field2" value="" /></td></tr>
<tr><td> Field Name 4:</td><td><input name="field3" value="" /></td></tr>
<tr><td> Field Name 5:</td><td><input name="field4" value="" /></td></tr>
</table>
<input type="submit" />
</form>
</body>
</html>

ommaconv.phphandles the data conversion.
 PHP that converts data from CSV just as easily as from XML or SQL
<html><body>
<div style="font-family:courier; font-size:small;">
$data = array(<br/>
<?
$fieldnames = array(
  $_POST['field0' ],
  $_POST['field1' ],
  $_POST['field2' ],
  $_POST['field3' ],
  $_POST['field4' ] );
$rows = split( "\n", $_POST['data'] );
$index = 0;
foreach( $rows as $row )
{
  if ( $index != 0 )
    print( ",<br/>" );
  $index++;
	  print( " array(" );
  $fields = split( ",", $row );
  for( $f = 0; $f < count( $fields ); $f++ )
  {
	  
    $data = $fields[ $f ];
	$data = preg_replace( "/\\\\\"/", "\"", $data );

	if ( $f > 0 )
	  print( ", " );
	print( $fieldnames[ $f ] );
	print( " => " );
	print( $data );
	}
	print( " )" );
  }
  ?><br/>
  );
  </div>
  </body></html>
Related Posts:
  • Length of a String The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string: integer strlen(string subject) We used strlen( ) earlier in the chapter t… Read More
  • Creating Arrays PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use: $numbers = array(5, 4, 3, 2, 1);… Read More
  • PHP Date / Time Functions checkdate — Validate a Gregorian date date_add — Alias of DateTime::add date_create_from_format — Alias of DateTime::createFromFormat date_create — Alias of DateTime::__construct date_date_set — Alias of DateTime::setDate … Read More
  • PHP Array Functions array_change_key_case — Changes all keys in an array array_chunk — Split an array into chunks array_combine — Creates an array by using one array for keys and another for its values array_count_values — Counts all the value… Read More
  • Defining Functions There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement: function some_function([argumen… Read More
  • Including and Requiring PHP Files To make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program… Read More
  • PHP Zip File Functions zip_close — Close a ZIP file archive zip_entry_close — Close a directory entry zip_entry_compressedsize — Retrieve the compressed size of a directory entry zip_entry_compressionmethod — Retrieve the compression meth… Read More
  • Php Directory Functions chdir — Change directory chroot — Change the root directory closedir — Close directory handle dir — Return an instance of the Directory class getcwd — Gets the current working directory opendir — Open directory handle read… Read More
  • Showing the Browser and IP Address Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your bro… Read More
  • Php Mysql Image upload <?php // 1. Gem modtagne formulardata i variabler: $navn = $_POST['navn']; $alder = $_POST['alder']; $postnr = $_POST['postnr']; $mail = $_POST['mail']; $billede = $_FILES['profilbillede']; $password = $_PO… Read More
  • PHP - Echo <?php $myiString = "Hi!"; echo $myiString; echo "<h5>I love PHP!</h5>"; ?>   Display: Hi! I love  PHP!  A simple form example     1 <html> 2 <head> 3 <title&g… Read More
  • PHP MySQL Functions mysql_field_len — Returns the length of the specified field mysql_field_name — Get the name of the specified field in a result mysql_field_seek — Set result pointer to a specified field offset mysql_field_table — Get … Read More
  • PHP Configuration Directives Although the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the cod… Read More
  • PHP Data Types PHP provides four primitive data types: integers, floating point numbers, strings, and booleans. In addition, there are two compound data types: arrays and objects.  Integers Integers are whole numbers. The range… Read More
  • File Manipulation 11.3. File Manipulation There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't co… Read More