所以我已经创建了php文件,从Arduino脉冲传感器接收脉冲数据,并将其存储到.txt文件中。下面是代码:
<?php
$pulse = $_GET["pulse"] ;
$file = fopen("data.txt", "a+");
$pulse.="'r'n";
fwrite($file, $pulse);//takes incoming data and writes it in the file
fclose($file);?>
所以我在我的data.txt中存储的只是一堆脉冲传感器的数字。我想从另一个php文件中访问data.txt作为json对象,所以我想出了这个,但它似乎不起作用:
<?php
header('Content-type: application/json');
if(isset($_GET["request"])){
if($_GET["request"] == "info"){
$pulse = $_GET["pulse"];
$file = fopen("data.txt", "a+");
$pulse.="'r'n";
fwrite($file, $pulse);
fclose($file);
echo json_encode($file);
}
}
?>
欢迎任何建议,我有一种感觉这是可能的。
,
这是我能想出的最简单的…
<?php
header('Content-type: application/json');
// make your required checks
$fp = 'yourfile.txt';
// get the contents of file in array
$conents_arr = file($fp,FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "'r");
}
var_dump($conents_arr);
$json_contents = json_encode($conents_arr);
echo $json_contents;
?>
这将首先将文件内容转换为数组,然后从中生成json。预期输出将类似于["data1","data2","data3"]
希望对你有所帮助
这将给你你想要的…
<?php
header('Content-type: application/json');
echo json_encode( explode("'r'n",file_get_contents('data.txt')) );
?>
如果你想发送数据文件的实际内容,你只需要读取文件的数据,将这些数据存储到一个数组中,然后使用json_encode
<?php
// Send header for json content
header('Content-type: application/json');
//检查用户是否询问info如果(!空($ _GET["请求"]),,$_GET["request"] == "info") {
// Retrieve the content of the file and split on "'r'n"
// ($data is an array of lines)
$data = preg_split("/'r'n/", file_get_contents("data.txt"));
// JSON encode the data array
echo json_encode($file);
}
假设脉冲数据是一个简单的整数,例如,您将发送一个JSON:
["12","24","20",....]