Alligator
Alligator

Reputation: 43

I need to pull data with PHP every 10 seconds

I set up a very small (internal) dedicated web server, and I need to pull some energy data every 10 seconds or so from an XML file. This is the PHP code I have thus far:

 <?php 
    $mydata = simplexml_load_file('http://192.168.x.xx:yyy/data.xml');

    echo $mydata->device[0]->name;
    echo $mydata->device[0]->value;
 ?>

I tested similar code out on my web server and PHP is installed and I think this should work, but I'd like to have this run every 10 seconds or so. This way the data displaying on my web page is always up to date. The web page will be left running 24/7 as a sign on the wall. What's the easiest way to refresh the data?

Upvotes: 1

Views: 1088

Answers (4)

Stegrex
Stegrex

Reputation: 4024

assuming you are running the server in Linux/Unix, perhaps look into writing a cronjob (automated job) for it?

One solution I can think of is to run the PHP script as a cronjob every 10 seconds, writing the output into a file or a database table.

You can then write a separate PHP script that reads the contents of the file/DB entry whenever anyone loads it in a browser.

Upvotes: 0

Marcel
Marcel

Reputation: 6310

If you are running this through a browser then I would go with Eric's answer.

However if you have this running from command line you can do one of the two:

  1. Have your current script say pull_energy_data.php to run from a cron job every 10 seconds. Don't forget to create some sort of locking mechanism. Just in case the job takes more than 10 seconds to run and you'll have more than one script running at the same time.

  2. Another approach is having a script wrapping your pull_energy_data.php running in a loop and executing it every 10 seconds. This is less desirable than the previous approach as you'll need to keep track of when pull_energy_data.php last ran and how to issue a command to stop the wrapper script.

Upvotes: 0

sachleen
sachleen

Reputation: 31131

The easiest way? Add this line to your page.

<meta http-equiv="refresh" content="10">

This may not be the best way though, especially if you have a lot of stuff on the page that you don't need reloaded every 10 seconds. If that's the case, you should look into AJAX.

If you have a page setup that returns only the data you need (like your example) you can make an asynchronous request every 10 seconds using JavaScript's setInterval() to get the latest data and show it.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

I would simply refresh the portion of the web page that displays the data using Ajax. Trigger the refresh using a JavaScript timer.

Upvotes: 4

Related Questions