GetSimple Support Forum

Full Version: external text file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
can i achieve this in GetSimpleCMS?

I have a temperature sensor wich puts it's last measure in a text file
Can i read this value from the text file and show it on the website?
Can anyone let me know if it's possible, and how to achieve this?

Thanks
Ben
You could add something like this in your template.php file:

Code:
$file = '/path/to/your/file.txt';
if(file_exists($file)) {
   $content = htmlspecialchars(file_get_contents($file), ENT_COMPAT, 'utf-8', false);
   echo $content;
} else {
   echo 'Error: '  .$file. 'does not exists'
}
A complete example would be...




PHP Code:
<?php


  $filename 
"test.dat";
  
  
while (1) {
    $filecontents read_file($filename);
    $content htmlspecialchars($filecontentsENT_COMPAT'utf-8'false);
    echo $content;   
    flush
();
    ob_flush();    
    sleep
(60);  // read temperature every 60 seconds
  }

  /* +-------------------------------------------------------+
     |                  read file - function                 |
     |  file can be any qualified path including web urls.   |
     |  $filename = "http://www.example.com/some/file.txt"   |
     +-------------------------------------------------------+ */
    
  
function read_file($filename) {
    if (file_exists($filename)) {
      $filedata file_get_contents($filename);
      return $filedata;
    } else {
      echo "File not found";
    }
  }

?>
Infinite loops are not really a good practice server-side, you should try to avoid the while(true) idiom whenever it possible. PHP is not suitable for real time applications, Ajax call more suitable for this purpose.
Yeah a meta refresh is just as easy if you want a live display, ideally use js or sockets, infinite flush will tie up a socket and everntually probably crash
(2016-05-07, 03:12:01)Bigin Wrote: [ -> ]Infinite loops are not really a good practice server-side, you should try to avoid the while(true) idiom whenever it possible. PHP is not suitable for real time applications, Ajax call more suitable for this purpose.

OK... so how about an example for comparison?
Well the poster didn't ask for a real time display, just to read a file