Difference between revisions of "JSON from arduino to PHP server"
From Wiki2
(Created page with "=====JSON from arduino to PHP server===== Encoding pin values in JSON: <sytaxhighlight> // last pieces of the HTTP PUT request: client.println("Content-Type: applicati...") |
|||
Line 11: | Line 11: | ||
for (int analogChannel = 2; analogChannel < 6; analogChannel++) { | for (int analogChannel = 2; analogChannel < 6; analogChannel++) { | ||
int sensorReading = analogRead(analogChannel); | int sensorReading = analogRead(analogChannel); | ||
String schan = "\"" | String schan = "\"sensor" + analogChannel + "\":"; | ||
client.print(schan); | client.print(schan); | ||
client.print(sensorReading); | client.print(sensorReading); | ||
Line 20: | Line 20: | ||
client.println("}"); | client.println("}"); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Reading arduino JSON from PHP server: | |||
<sytaxhighlight> | <sytaxhighlight> | ||
<?php | |||
$thefile=file_get_contents("php://input"); | |||
echo "I want ".sizeOf($thefile)." of them\n\n"; | |||
echo ($thefile); | |||
$thearray = json_decode($thefile); | |||
print_r($thearray); | |||
?> | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Output produced: | |||
<sytaxhighlight> | <sytaxhighlight> | ||
{"sensor2":376,"sensor3":349,"sensor4":251,"sensor5":285} | |||
stdClass Object | |||
( | |||
[sensor2] => 376 | |||
[sensor3] => 349 | |||
[sensor4] => 251 | |||
[sensor5] => 285 | |||
) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<sytaxhighlight> | <sytaxhighlight> | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 15:15, 12 January 2013
JSON from arduino to PHP server
Encoding pin values in JSON: <sytaxhighlight>
// last pieces of the HTTP PUT request: client.println("Content-Type: application/json"); client.println("Connection: close"); client.println(); client.print("{"); // here's the actual content of the PUT request: for (int analogChannel = 2; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); String schan = "\"sensor" + analogChannel + "\":"; client.print(schan); client.print(sensorReading); if (analogChannel != 5) { client.print(","); } } client.println("}");
</syntaxhighlight> Reading arduino JSON from PHP server: <sytaxhighlight> <?php $thefile=file_get_contents("php://input");
echo "I want ".sizeOf($thefile)." of them\n\n"; echo ($thefile); $thearray = json_decode($thefile); print_r($thearray);
?> </syntaxhighlight> Output produced: <sytaxhighlight> {"sensor2":376,"sensor3":349,"sensor4":251,"sensor5":285} stdClass Object (
[sensor2] => 376 [sensor3] => 349 [sensor4] => 251 [sensor5] => 285
) </syntaxhighlight> <sytaxhighlight> </syntaxhighlight>