1+ <?php
2+
3+ $ cwd = dirname (realpath (__FILE__ ));
4+ $ zipfile = $ cwd . '/zip-codes-database-FREE.csv ' ;
5+ if (!file_exists ($ zipfile )) {
6+ echo "Error: Take the latest free zip code database from zip-codes.com and extract the CSV next to this file and try again. \n" ;
7+ exit (1 );
8+ }
9+
10+
11+ echo "Cleaning any previous build... \n" ;
12+ clean ($ cwd );
13+
14+ $ row = 0 ;
15+ $ headers = [];
16+ if (($ handle = fopen ($ zipfile , 'r ' )) !== false ) {
17+ while (($ data = fgetcsv ($ handle , 1000 , ', ' )) !== false ) {
18+ if ($ row == 0 ) {
19+ $ headers = $ data ;
20+ } else {
21+ $ zip = new stdClass ();
22+ foreach ($ data as $ key => $ value ) {
23+ $ keyname = $ headers [$ key ];
24+ $ zip ->{$ keyname } = $ value ;
25+ }
26+ if (!empty ($ zip ->ZipCode )) {
27+ echo "Creating files for " . $ zip ->ZipCode . "\n" ;
28+ file_put_contents ($ cwd . '/ ' . $ zip ->ZipCode . '.json ' , json_encode ($ zip ));
29+ file_put_contents ($ cwd . '/ ' . $ zip ->ZipCode . '.jsonp ' , 'zipCodeCallback( ' . json_encode ($ zip ) . '); ' );
30+ }
31+ }
32+ $ row ++;
33+ }
34+ fclose ($ handle );
35+ }
36+
37+ /**
38+ * Recursively delete files and folders within a directory based on type.
39+ * @param $dir
40+ * @param null $root
41+ * @param array $types
42+ */
43+ function clean ($ dir , $ root = null , $ types = ['json ' , 'jsonp ' ])
44+ {
45+ if (!$ root ) {
46+ $ root = $ dir ;
47+ }
48+ if (is_dir ($ dir )) {
49+ $ objects = scandir ($ dir );
50+ foreach ($ objects as $ object ) {
51+ if ($ object != ". " && $ object != ".. " ) {
52+ if (is_dir ($ dir ."/ " .$ object )) {
53+ clean ($ dir ."/ " .$ object , $ root , $ types );
54+ } else {
55+ $ ext = pathinfo ($ object , PATHINFO_EXTENSION );
56+ if (in_array ($ ext , $ types )) {
57+ unlink ($ dir ."/ " .$ object );
58+ }
59+ }
60+ }
61+ }
62+ if ($ dir !== $ root ) {
63+ try {
64+ rmdir ($ dir );
65+ } catch (Exception $ e ) {
66+ }
67+ }
68+ }
69+ }
0 commit comments