O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #43. Convert CSV to PHP

Use PHP to create PHP data arrays from comma-separated value (CSV) datafiles.

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.

The publisher table as shown in the browser

Figure 5-7. The publisher table as shown in the browser

The Code

Save the code in Example 5-31 as index.php.

Example 5-31. Page that sets up some comma-separated values to convert

<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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required