简体   繁体   English

php 将 javascript 变量回显到 file.txt

[英]php echo a javascript variable to file.txt

I've this code that works fine to get the user Timezone and echo in php.我有这段代码可以很好地获取用户时区并在 php 中回显。 There's also an alert message before.之前还有一条警告消息。

<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script> <script> var timezone =
Intl.DateTimeFormat().resolvedOptions().timeZone; alert(timezone);
</script>
<?php
$time= "<script>document.writeln(timezone);</script>";
echo $time;

I want to store this echo in the file time.txt我想将此回声存储在文件 time.txt 中

I've tried with this:我试过这个:

$file_name = 'time.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'w') or die('Cannot open file: '.$file_name);
// write name to the file
fwrite($myfile, $time);
// close the file
fclose($myfile);

but it doens't work .但它不起作用。

Any solutions?任何解决方案?

It seems like what you want is for PHP to write the file with the result of the timezone variable, ie that it would be a text file with the name of a timezone in it.似乎您想要的是 PHP 用时区变量的结果编写文件,即它是一个包含时区名称的文本文件。

Probably what you are seeing is PHP writing that JavaScript line instead, ie <script>document.writeln(timezone);</script>可能您看到的是 PHP 编写了该 JavaScript 行,即<script>document.writeln(timezone);</script>

Right?对?

What's happening is PHP executes completely before JavaScript is run.发生的事情是 PHP 在运行 JavaScript 之前完全执行。 Your first example is working because PHP executes, including the writing of a line of JavaScript, and then JavaScript executes, including that line, and you see the result.您的第一个示例正在运行,因为 PHP 执行,包括编写一行 JavaScript,然后 JavaScript 执行,包括该行,您会看到结果。

What you are trying to do in the second example isn't possible.您在第二个示例中尝试执行的操作是不可能的。 PHP is executing, including the writing of that line of JavaScript (to the file), and then JavaScript executes, but of course not in that text file. PHP 正在执行,包括将那行 JavaScript 写入(到文件),然后 JavaScript 执行,但当然不是在那个文本文件中。

Your two choices are to find a different way to get the timezone strictly in PHP, or else to get it with JavaScript and then use AJAX to trigger a later run of PHP, ie after JavaScript has run.您的两个选择是找到一种不同的方法来严格地在 PHP 中获取时区,或者使用 JavaScript 获取时区,然后使用 AJAX 触发稍后运行的 PHP,即在 JavaScript 运行之后。

EDIT编辑

Your JavaScript will fetch the timezone as before.您的 JavaScript 将像以前一样获取时区。 Then it will send that to a separate file that outputs it:然后它会将它发送到一个单独的文件输出它:

var url = '..'; // url of a php file that JUST processes the file write
$.ajax({
  type: "POST",
  url: url,
  data: {
        'timezoneToPrint' : timezone
    }
});

And in your other PHP file, which you have just called, you can now print it to a file在您刚刚调用的另一个 PHP 文件中,您现在可以将其打印到一个文件中

if($_POST['timezoneToPrint']){
   // ..write the file here, the timezone is in $_POST['timezoneToPrint']
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM