Categories: Development

Another PHP simple DOM selection

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.

Share
Tags: PHPWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago