1


Arduinoセンサーからいくつかの値を取得し、それらをphp Webサーバーに渡して計算を行い、jsonファイルに保存しようとしています。残念ながら、私はjsonについてあまり知りません。
私の問題は、データが JSON ファイルに正しく挿入される一方で、別の関数からデータを読み戻そうとすると、正しいキーを取得するが NULL 値を取得することです。
POST リクエストから値を取得し、JSON ファイルに保存する関数を次に示します。

<?php 
include 'handledata.php';
//take data from POST
$light=$_POST["light"];
$temp=$_POST["temp"];

$sensors = array('light'=>$light, 'temp'=>$temp);
$fp=fopen('sensors.json', 'w');
fwrite($fp, json_encode($sensors));
fclose($fp);

echo "Sensor updated: calling data handler..\n";

handleData();
?>

このコードは実際に機能します。出力 sensor.json は次のようになります。

{"light":"300","temp":"22"}

これは handleData() 関数のコードです:

<?php
function handleData(){
    $json = file_get_contents('./sensors.json', true);
    var_dump($json);
    $sensors=json_decode($json, true);
    var_dump($sensors);
}
?>

2 つのダンプは次のようになります。

string(26) "{"light":null,"temp":null}"
array(2) { ["light"]=> NULL ["temp"]=> NULL }

私が今までやろうとしていたのは、json ファイルを変更することです (最初の関数): 数値を含む文字列として値を供給する代わりに、次のように int と文字列を供給しました:

$l=intval($light);
$sensors = array('light'=>$l, 'temp'=>"eight");

これで、sensors.json は次のようになります。

{"light":793,"temp":"eight"}

そして、handleData の出力は次のようになります。

string(26) "{"light":0,"temp":"eight"}" 
array(2) { ["light"]=> int(0) ["temp"]=> string(5) "eight" }

何が問題なのかについてのアイデアがありません。文字列「8」では機能しましたが、文字列「300」では機能しませんでした。また、整数と数値の解析に関して何か不足していますか? ありがとう。

4

2 に答える 2