当新信息写入文件时,如何使用 PHP 动态读取文件

How do I dynamically read from a file using PHP as new information is written into it

我设置了一个代码,我使用 JS 和 PHP 写入文件并将输出显示到 html 元素(在本例中为文本区域)。我对如何解决这个问题有很大的疑问。我知道 PHP 在其他任何事情发生之前执行。我使用 php 使用我自己的 javascript 函数

回显文件内容
output(string) // this outputs whatever into the html element text area

PHP:

<?php echo "output('".$someText."');"; ?>

现在,当我更新并向该文件添加内容时,我的问题出现了,但是 php 已经执行并尝试再次从文件中读取,只会显示上次执行的结果php。解决此问题的唯一方法是刷新页面,从而 'rebuilding' 文件的 html 内容。

我的整个代码模仿了命令行的外观(你有一个带输入框的输出屏幕)我如何在不向文件添加新内容时动态显示文件内容必须刷新 window。刷新 window 会起作用,但根本不是我需要的。有什么帮助吗?

有关我的代码结构的更多信息,您将在下面找到代码执行方式的片段:

// main.php
<?php
    // displays the file into the output box
    function displayFile($fileName){
        $file_handler = fopen($fileName, "r");
        while (!feof($file_handler)){
            $line = fgets($file_handler);
            $line = formatFileLine($line);
            echo "output('".$line."');";
        }

        fclose($file_handler);
    }
?>

switch(splitCmd[1]){
    case 'permitted':
        output('\nWells that have been permitted:\n');
        <?php displayFile('permitted.txt'); ?> //calls the php function to display content.
        break;
    case 'drilled':
        output('\nWells that have been drilled:\n');
        <?php displayFile('drilled.txt'); ?>
        break;
    default:
        output('Wrong syntax: show <permitted, drilled>');
}

您可以通过 AJAX 请求来做到这一点,有多种方法可以做到这一点,但最简单的方法是使用 jQuery(当然是基于意见!),这里是 link 到文档。 jQuery AJAX

示例:

function ajaxCall(){

$.ajax({ url: 'PHPFILE.php',
        success: function(e){

            //e is what you get returned from the php file
            $('#div').html(e);
        }
    });
}

哦,您当然应该 jquery 库 linked。你这样做:

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

您需要对 PHP 文件进行 AJAX 调用。从 PHP 脚本中获取输出,并将其嵌入到页面上的给定 div 中。

假设您有一个 div 用于展示。让我们给你一个按钮,随时刷新它。

<div id="resultdiv"></div>
<input type = "button" id="rbutton" value="Click to Refresh">

随意设置样式。

现在,让我们设置一个 AJAX 调用来从 PHP.

加载结果
<script type="text/javascript">

    $(function() {  //document ready psuedonym

       function refreshdata(){

$.ajax({
        type: "POST",
        url: "my_data_script.php",
        dataType: 'html',
        data: {myparam1: 'abc', myparam2: '123'},  //these are optional parameters in case your PHP script needs them

    success: function(data){
        $('#resultdiv').html(data);
        },

        error: function(){
        },

        complete: function(){
        }
    }); //end ajax  

       }  //end function 

    $("#rbutton").click(function() {  //clicking the button refreshes the data on demand
        refreshdata();
    });

       refreshdata();  //this will run the function when the page loads


    });//end document ready pseudonym
</script>