WordPress: reperire i dati da una stazione climatica

WordPress: reperire i dati da una stazione climatica

Reperire i dati da una stazione climatica non è un'operazione troppo complessa in WordPress.

Dobbiamo ottenere il file remoto dei dati, salvarne una copia cache, effettuarne il parsing e creare un'API JSON per permettere a JavaScript di usare i dati tramite AJAX. Possiamo creare la seguente classe:


class My_Stats {

    const STATS_URL = 'http://IP/data.html'; // O come opzione del tema
    
    public function __construct() {
      add_action( 'wp_ajax_my_stats', array( &$this, 'getMeteoData' ) );
      add_action( 'wp_ajax_nopriv_my_stats', array( &$this, 'getMeteoData' ) );
    }

    /* Otteniamo il file remoto */

    public function getStats() {
        $output = '';
        $opts = array( 'timeout' => 5 );
        $request = wp_remote_get( self::STATS_URL , $opts );
        if( !is_wp_error( $request ) ) {
            $output = $request['body'];
        }
        return $output;
    }

    /* Salviamo il file remoto come copia locale (cache) */

    public function saveStats() {
      $data = $this->getStats();
      $output = '';
      $base = get_template_directory_uri() . '/meteodata/';
      if( !empty( $data ) ) {
        file_put_contents( TEMPLATEPATH . '/meteodata/' . 'data.html', $data );
        $output = $base . 'data.html';
      } else {
        $output = false;
      }
      return $output;
    }

    /* Verifichiamo che il file remoto sia stato salvato */

    public function haveStats() {
        $base = TEMPLATEPATH . '/meteodata/data.html';
        return file_exists( $base );
    }

    /* Azione AJAX: trasformiamo il documento HTML
     * in un oggetto JSON selezionando gli elementi
     * e i loro attributi
     */

    public function getMeteoData() {
  			$output = array();
        $data = $this->saveStats();
        if( !is_bool( $data ) && !empty( $data ) ) {
            if( $this->haveStats() ) {
                $doc = new DOMDocument();
                $file = TEMPLATEPATH . '/meteodata/data.html';
                $doc->loadHTMLFile( $file );
                $inputs = $doc->getElementsByTagName( 'input' ); // In questo caso i dati sono elementi input
                if( !is_null( $inputs ) ) {
                    foreach( $inputs as $input ) {
                        $name = $input->getAttribute( 'name' );
                        $value = $input->getAttribute( 'value' );
                        $d = array();
                        $d[$name] = $value;
                        $output[] = $d;
                    }
                }
            }
        }
  			header( 'Content-Type: application/json' );
  			echo json_encode( $output );
  			exit();
  	}
}

Quindi in functions.php:


require_once( TEMPLATE_PATH . '/framework/My_Stats.php' );

$myStats = new My_Stats();

A questo punto con AJAX e JavaScript possiamo visualizzare i dati nella pagina.

Torna su