<?php
// fhexample.php
// Metadata Labs Firehose example

// Base request url
$requestUrl = "http://api.metadatalabs.com/firehose.php?fmt=json";

// how often to make requests, in seconds
$requestFrequency = 30;

// last update time, for making conditional GET requests
$lastUpdateTime = 0;

for (;;)
{
    print "requesting $requestUrl\n";
    $response = http_get($requestUrl, 
        array(
            "timeout"=>30,
            "lastmodified"=>$lastUpdateTime, // sets If-Modified-Since header
            "compress"=>true),  // requests compressed, to conserve bandwidth
        $info);
    $response_code = $info['response_code'];
    if ($response_code == 304)
    {
        // Not Modified
        print "Not modified\n";
    }
    else if ($response_code == 200)
    {
        $msg = http_parse_message($response);
        
        // get and save the last update time
        $lastUpdateTime = strtotime($msg->headers['Last-Modified']);
        $body = $msg->body;

        if (body)
        {
            // Process the returned data here.
            print $body . "\n";
        }
        else
        {
            print "ERROR: No body in message.\n";
        }
    }
    else
    {
        // some kind of error.
        print "ERROR: $response_code\n";
    }

    print "waiting $requestFrequency seconds . . .";
    
    sleep($requestFrequency);
    
    print "\n";
}