I have touched on PHP Simple HTML DOM parser before, its useful to grab data from websites where no API is available. It’s actually one of the many methods.. such as using native PHP DOM document or cURL which I will show in this post combined with PHP simple DOM.
The idea was to get the water level for reservoir/s and the date it was updated. Firstly a function utilizing cURL to get the webpage contents:
function get_html($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
$data = curl_exec($ch);
curl_close($ch);
return str_get_html($data);
} This returns the URL in HTML format
Now just using the find method with selectors to pinpoint that data:
$html = get_html('https://theurl.com/page');
$level = $html->find('tr.capacityPercentage td', 0)->innertext;
$updated = $html->find('span.value', 0)->innertext; This is the pure html for the section of the page i was interested in:
Water Storage Levels
Last Updated 25/02/2019
53.2% 51.0% 49.4% 45.8% 42.9%Oct Nov Dec Jan Feb
Current Volume 130785 % of Capacity 42.93 Capacity (ML) 304651
To get the water level percent (42.93) i filtered
with class of “capacityPercentage” and the inner text of the first (0) child. For the updated date (25/02/2019); The inner text of the first (0) with a class of “value” .
You can read more on PHP Simple DOM selectors here.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…