followed by a linefeed character (ASCII 10)
< ozone > followed by a linefeed character (ASCII 10)
null character (ASCII 0)
*/
// url of the page with the air quality index data for New York City:
$url = 'http://airnow.gov/index.cfm?action=airnow.showlocal&cityid=164';
$readParticles = 0; // flag telling you the next line is the particle value
$readOzone = 0; // flag telling you the next line is the ozone value
$particles = -1; // the particles value
$ozone = -1; // the ozone value
// open the file at the URL for reading:
$filePath = fopen ($url, "r");
// as long as you haven't reached the end of the file
while (!feof($filePath))
{
// read one line at a time, and strip all HTML and PHP tags from the line:
$line = fgetss($filePath, 4096);
// if the previous line was the "observed at line" preceding
// the particle matter reading, then $readParticles = 1 and
// you should get this line, trim everything but the number,
// and save the result in $particles:
if ($readParticles == 1) {
$particles = trim($line);
echo "< AQI: $particles>";
$readParticles = 0;
}
// if the previous line was the "observed at line" preceding
// the ozone reading, then $readOzone = 1 and
// you should get this line, trim everything but the number,
// and save the result in $ozone:
if ($readOzone == 1) {
$ozone = trim($line);
//echo "<$ozone>";
$readOzone = 0;
}
// if the current line contains the substring "AQI observed at"
// then the line following it is either the particle reading
// or the ozone reading:
if (preg_match('/AQI observed at /', $line)) {
// if $particles == -1, you haven't gotten
// a value for it yet, so the next line
// till be the particle value:
if ($particles == -1) {
$readParticles = 1;
}
// if $particles > -1, you've gotten a value for it.
// that means that the next line will be the
// ozone reading, if you haven't already gotten
// a reading for ozone (i.e. if $ozone == -1):
if (($particles > -1) && ($ozone == -1)) {
$readOzone = 1;
}
}
}
// close the file at the URL, you're done:
fclose($filePath);
?>