· 5 years ago · Nov 07, 2020, 05:54 PM
1<?PHP
2/**
3 * Demonstrates using the OpenFDA API.
4 */
5
6function get_api_key_form() {
7 $frm = "<p>Please enter you API Key.</p>\n
8 <form method=\"post\" action=\"\">\n
9 API Key: <input type=\"text\" name=\"api_key\">\n
10 <input type=\"submit\">\n
11 </form>\n";
12
13 return $frm;
14}
15
16function save_data($fname, $data) {
17 $fh = fopen($fname, 'w');
18 fwrite($fh, $data);
19 fclose($fh);
20}
21
22try {
23 $foodFile = './food.json';
24 $ddFile = './dropdown_list.html';
25
26 /* Main application config file. */
27 $mainConfigFile = __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app-main.php';
28 if (!file_exists($mainConfigFile)) throw new Exception("ERROR: Could not locate application config file.");
29 include_once($mainConfigFile);
30
31 /* Header file for HTML. */
32 $headerFile = __DIR__ . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . 'header.php';
33 if (!file_exists($headerFile)) throw new Exception("ERROR: Could not locate HTML header file.");
34 $pageTitle = "Customers DEMO";
35 include_once($headerFile);
36
37 if ($_SERVER["REQUEST_METHOD"] == "POST") {
38
39 if (!empty($_POST['api_key'])) {
40 /* Get list. */
41 $api_key = filter_input(INPUT_POST, 'api_key', FILTER_SANITIZE_SPECIAL_CHARS);
42 $msg = "<p>API Key = {$api_key}<p>";
43 $url = "https://api.nal.usda.gov/fdc/v1/foods/search?api_key={$api_key}";
44 $data = [
45 'collection' => 'food'
46 ];
47 $curl = curl_init($url);
48 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
49 curl_setopt($curl, CURLOPT_POST, true);
50 curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
51 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
52 curl_setopt($curl, CURLOPT_ENCODING, "");
53 curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
54 curl_setopt($curl, CURLOPT_TIMEOUT, 30);
55 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
56 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
57 curl_setopt($curl, CURLOPT_HTTPHEADER, [
58 "x-rapidapi-host: developer.nrel.gov",
59 "x-rapidapi-key: Wz1LagBw8fyMm2JfRYeiZjc0tpwnM24ACi1vY3nS",
60 "Content-Type: application/json"
61 ]);
62 $response = curl_exec($curl);
63 if(!empty($response)) {
64 /* Save most recent list to file. */
65 save_data($foodFile, $response);
66 } else {
67 /* Read previously saved list when no response. */
68 if (!file_exists($foodFile)) throw new Exception("ERROR: Could not locate JSON food file.");
69 $response = file_get_contents($foodFile);
70 }
71 curl_close($curl);
72
73 $json = json_decode($response, true);
74
75 $y = 0;
76 $option = '';
77 foreach ($json['foods'] as $food):
78 $option = $option . "<option value={$y}>{$food['description']} {$food['brandOwner']}</option>\n";
79 $y++;
80 endforeach;
81
82
83 $msg = $msg . "
84 <form action=\"\" method=\"post\">\n
85 <input type=hidden name=p3 value=3>\n
86 <label for=\"select1\">Select</label>\n
87 <select style=\"width: 400px\" id=\"\select1\" name=\"select1\">\n
88 {$option}
89 </select>\n
90 <button type=\"submit\" id=\"submit\">Submit</button>\n
91 </form>
92 ";
93
94 save_data($ddFile, $msg);
95
96 } elseif (!empty($_POST['p3'])) {
97 /* Get Food Info. */
98 $foodFile = './food.json';
99 if (!file_exists($foodFile)) throw new Exception("ERROR: Could not locate JSON food file.");
100 $json = file_get_contents($foodFile);
101 $json = json_decode($json, true);
102
103 $y = filter_input(INPUT_POST, 'select1', FILTER_SANITIZE_SPECIAL_CHARS);
104 $msg = "FDC Id: {$json['foods'][$y]['fdcId']}<br/>\n
105 Description: {$json['foods'][$y]['description']}<br/>\n";
106
107 if (empty($json['foods'][$y]['brandOwner'])) {
108 $msg = $msg . 'Company:';
109 } else {
110 $msg = $msg . "Company: {$json['foods'][$y]['brandOwner']}\n";
111 }
112
113 $x = 0;
114 while ($x <= 13) {
115 $msg = $msg . "{$json['foods'][$y]['foodNutrients'][$x]['nutrientName']}
116 {$json['foods'][$y]['foodNutrients'][$x]['nutrientNumber']} {$json['foods'][$y]['foodNutrients'][$x]['unitName']}<br>\n";
117 $x++;
118 }
119
120 if (!file_exists($ddFile)) throw new Exception("ERROR: Could not locate file for drop-down list.");
121 $msg = $msg . file_get_contents($ddFile);
122 } else {
123 /* Get API Key. */
124 $msg = "<p>No form data found.<p>" . get_api_key_form();
125 }
126 } else {
127 $msg = get_api_key_form();
128 }
129
130 /* Display output. */
131 echo $msg;
132
133 /* Footer file for HTML. */
134 $footerFile = __DIR__ . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . 'footer.php';
135 if (!file_exists($footerFile)) throw new Exception("ERROR: Could not locate HTML footer file.");
136
137} catch (Exception $e) {
138 list($sTag, $eTag) = array("\n", "\n");
139 if (file_exists($headerFile)) list($sTag, $eTag) = array("\n<p class=\"error\">", "</p>\n");
140 $msg = "{$sTag}{$e->getMessage()}{$eTag} {$sTag}See on line # {$e->getLine()} in file {$e->getFile()}{$eTag}";
141 echo($msg);
142} finally {
143 if (file_exists($headerFile)) {
144 include_once($footerFile);
145 }
146}