Hardware Reference
In-Depth Information
To extract the data
you need from
those lines, you'll need a couple more
variables. Add this code before the
fopen() command.
Scrape It
// whether you should check for a value
// on the line you're reading:
$checkForValue = false;
// value of the Air Quality reading:
$airQuality = -1;
Replace the command echo $line;
in the program with the block of code
at right.
8
// if the current line contains the substring "Current Conditions"
// then the next line with an integer is the air quality:
if (preg_match('/Current Conditions/', $line)) {
$checkForValue = true;
}
This block uses the preg_match()
command to look for a string of text
matching a pattern you give it. In this
case, it looks for the pattern Current
Conditions . When you see that line, you
know the next line is the number you
want. When the PHP script finds that
line, it sets the variable $checkForValue
to true.
Now, add the following block of
code after the one you just added. This
code checks to see whether $check-
ForValue is true, and whether the line
contains an integer and nothing else.
If so, the program reads the next line
of text and converts it from a string to
an integer value. It will only get a valid
integer when it reaches the line with
the AQI value.
8
if ($checkForValue == true && (int)$line > 0){
$airQuality = (int)$line;
$checkForValue = false;
}
8
Finally, add the following lines at
the end of the script, after the while
loop. This prints out the air-quality
reading and closes the connection to
the remote site.
echo "Air Quality:". $airQuality;
// close the file at the URL, you're done:
fclose($filePath);
The result in your web browser should
look like this:
Air Quality: 43
Now you've got a short string of text
that your microcontroller can read.
Even if the script got no result, the
value -1 will tell you that there was no
connection.
 
Search WWH ::




Custom Search