Grgo
Grgo

Reputation: 13

Extract specific data from website using php

I would like to get data from certain website. part of Html as follows:

<span class="last">10,750.00</span>

I would like to get out 10750 without comma and dot.

number 10,750.00 is just an example. This number is changing

Upvotes: 0

Views: 225

Answers (2)

Sampgun
Sampgun

Reputation: 2977

Starting from this:

<span class="last">anything here</span>

You could do:

$page = file_get_contents('http://www.example.com/');
$toSearch1 = '<span class="last">';
$toSearch2 = '</span>';

Get content and prepare search vars

$page = strstr($page, $toSearch1);
$page = strstr($page, $toSearch2, true);

This will extract only 'anything' and remove other unnecessary HTML

Then:

$page = strip_tags($page);

This will remove HTML tags, or, if you want to try manually

$page = str_replace($toSearch1, "", $page);
$page = str_replace($toSearch1, "", $page);

Finally

$page = str_replace(['.', ','], '' , $page);

Remove dots and commas

$page = substr($page, 0, -2);

Remove decimals

$page = (int)$page;

You can cast to int, even if PHP will handle automatically if you use the number to do calculations

Fiddle here ==> https://www.tehplayground.com/oqywfzmo2IWJdN0C

Upvotes: 1

Cava
Cava

Reputation: 5662

If you have the part of HTML in a variable, you can do this:

$html = '<span class="last">10,750.00</span>';
$without_tag = strip_tags($html); // Remove Tags HTML
$number_float = (float) str_replace(',', '', $without_tag); // Remove commas and change to float
echo $number_float; // 10750

If you do not have the HTML you can use:

$html = file_get_contents("http://example.com/");
$part = stristr(stristr($html, '<span class="last">'), '</span>', true);
$without_tag = strip_tags($part); // Remove Tags HTML
$number_float = (float) str_replace(',', '', $without_tag); // Remove commas and change to float
echo $number_float; // 10750

Upvotes: 0

Related Questions