简体   繁体   中英

Reading text file with php for javascript

I am trying to read a text file line by line updated by a python script with php. From there, I'm trying to convert it into javascript (for google maps API). I am stuck at converting php to javascript.

var line = <?php
    $file_handle = fopen('posts_replied_to.txt','r');
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        echo $line;
    }
    fclose($file_handle);
?>      

Will line keep changing every time $line does or will it only take the last $line value? I need to do operations for each line. Hopefully I made sense....

If you need to do javascript operations on each line, you'll want to store each line in an array element or similar:

<?php
    $arr = [];
    $file_handle = fopen('posts_replied_to.txt','r');
    while (!feof($file_handle)) {
        $arr[] = fgets($file_handle);
    }
    fclose($file_handle);
?>    
var lines = <?php json_encode($arr); ?>;

lines.forEach(function (line) {
  // do stuff with line
});

An even simpler method would be to pass javascript the entire file as a string, and split it by line breaks to make the array:

var file = <?php echo json_encode(file_get_contents('posts_replied_to.txt')); ?>;
var lines = file.split(/\r?\n/g);
lines.forEach(function (line) {
  // do stuff with line
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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