无法读取 PHP 中的 csv 并将其传递给 html 文件中的 javascript

Can't read csv in PHP and pass it to javascript in a html file

环境

我想做什么

最终目标

使用Raspberry Pi制作宠物监控系统。创建一个网页,您可以在其中检查宠物的流图像以及温度和湿度。

当前问题

无法使用 PHP 读取 csv 数据(温度和湿度)并将其传递给 html 文件中的 javascript。

下面给我一个空白页。

test.html

<?php
$data = array();
$fp = fopen('temphumid.csv', 'r');
$row = fgetcsv($fp); // skip the header
while ($row = fgetcsv($fp)) { $data[] = sprintf("['%d', %d, %d] ", $row[0], $row[1], $row[2]); }
$str = implode(', ' . PHP_EOL, $data);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ ['day', 'avg_temp', 'avg_humid'],
<?php $str; ?>
]);
var options = { title: 'This is a test graph' };
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 80%; height: 400px;"></div>
</body>
</html>

temphumid.csv 与 test.html.

在同一目录中

temphumid.csv

dateandtime,temp,humid
1,20.0701749938488,48.0275514992728
2,20.2401044696121,57.2354245801184
3,19.1474087424506,45.5657495890199
4,18.8319188605772,62.4405658353862
5,20.8854516366497,46.5185590247232
6,20.7459481702926,47.4137986506082
7,20.9609524855751,48.5064890268627
8,17.0936718055156,46.1276393517355
9,18.4273511669417,42.4825830307023
10,20.9669696456074,51.5502032331834

我尝试了很多方法,包括将 echo 添加到 php 子句,在 javascript 中硬编码示例数组等......都是徒劳的。

<?php echo $str; ?> 行更改为 [0, 5, 4], [1, 9, 10], [2, 20, 23] 即可。所以 PHP 有问题,但我不知道它是什么。

我也提到了这个post。 - How to pass variables and data from PHP to JavaScript? 但这没有帮助。

此外,javascript 控制台告诉我以下消息。

The console tells me Uncaught SyntaxError: Unexpected token <

我该如何解决这个问题?提前致谢。

更新1

我在 Raspberry Pi 的 Web 服务器中添加了 echo 和 运行 程序。但是,我仍然在控制台上看到空白页和 Uncaught SyntaxError: Unexpected token <

更新2

我将扩展名更改为 php,现在可以正常使用了。谢谢大家!

可能是因为 php 文件没有 .php 扩展名。尝试在 test.php.

中重命名 test.html

<?php $str; ?> 替换为 <?php echo $str; ?>,将文件的扩展名更改为 .php 而不是 .html,一切都会正常进行。

我写的一些类似的代码:

$seperator = $_POST['seperator'];
$escape = $_POST['escape'];
$default_val = $_POST['default_val'];
$files = $_FILES['filesToUpload']['name'];
$files_array = array();
//no files selected
if ($files[0] == "") {
    echo "You have to select at least 1 file";
    exit();
}
//preprocess by creating an array per file with it's path and name
$count = 0;
foreach ($files as $file) {
        $current_file = array();
        $current_file['name'] = $file;
        $current_file['path'] = $_FILES['filesToUpload']['tmp_name'][$count];
        $files_array[$file] = $current_file;
        ++$count;
}

$translation_array = array();
$languages = array();
foreach ($files_array as $file_key => $file_value) {
    $text_file = file($file_value['path']);
    $languages[] = $file_value['name'];

    foreach ($text_file as $line_number => $line) {
        $line = rtrim($line, "\n");
        $line_parts = explode('=', $line);
        $translation_key = $line_parts[0];
        if ($file_value['name'] != 'brndportal.properties') {
            $translation_array[$translation_key][$file_value['name']] = $line_parts[1];
        } else {
            $translation_array[$translation_key][$file_value['name']] = $line_parts[0];
        }
    }
}

$translation_csv = fopen("files/translation.csv", "w") or die("Unable to open file!");

//headers
$txt = "key" . $seperator;
foreach ($files as $file) {
    $txt .= $file . $seperator;
}

$txt .= "\n";
fwrite($translation_csv, $txt);

//translations
foreach ($translation_array as $translation_key => $translation_arr) {

    if (array_key_exists('brndportal.properties', $translation_array[$translation_key])) {
        $txt = '';
        $txt .= $translation_key . $seperator;

        foreach ($languages as $language) {
            if(array_key_exists($language, $translation_arr)) {
                $translation_value = $translation_arr[$language];
            }
            else {
                $translation_value = $default_val;
            }
            if (strpos($translation_value, $seperator) !== false) {
                $translation_value = $escape . $translation_value . $escape;
            }

            $txt .= $translation_value . $seperator;
        }

        $txt .= "\n";
        fwrite($translation_csv, $txt);
    }
}
fclose($translation_csv);

它读取 1 个或多个 CSV 文件并解析行。你可以插入你自己的分隔符和东西。

我认为最好将所有内容读取到数组并将其序列化为 JSON,这样您就可以通过 ajax 调用将其传递给 javascript。我建议在该部分使用 jQuery。

我在控制台上 Uncaught SyntaxError: Unexpected token < 遇到了同样的困难。

<?php echo $str; ?> 解决方案适用于某些变量。虽然我有一个数组。

所以我使用了 var myArray = <?php echo json_encode($myArray); ?> 并且成功了。