0

EDIT: Problem is (semi) fixed. Now when I cast the string it becomes and itege

I'm trying to fetch a series of pieces of data from the Steam website. One of these pieces of data is the price.

The web request I am making returns something similar to the following:

class=\"market_table_value\">\r\n\t\t\t\tStarting at:<br\/>\r\n\t\t\t\t<spanstyle=\"color:white\">&#36;9.05 USD<\/span>\r\n\t\t\t<\/span>\r\n\t\t\t<span

This is not the whole return, but it is the relevant section.

So I then use the following method to store it in an array (since the request usually has multiple items returned)

preg_match_all('#Starting\s*at:<br/>\r\n\t\t\t\t(.*)\t\t\t</span>#siU',$res->results_html, $sor);
foreach($sor[1] as $k => $v)
        $objects[$k]['price'] = $v; //str_replace('&#36', '', $v);

... and then I write object to a data.json file. Here is the formatting of the data.json (the relevant section.)

"price":"<span style=\"color:white\">&#36;0.48<\/span>\r\n"

The problem is, that when I try to cast the price into a float it returns 0. Here is my code for that section.

foreach($decodedfile as $datas) {
    $tmp = preg_replace(array("/[^0-9,.]/"), "", $datas->price);
    $ourprice = (float)$tmp;
    $sql2 = ("INSERT INTO Products (FileID, FileName, FileCat, FileType, FileMethod, FilePrice) VALUES ('".$id."', '".$datas->name."', '12', 'Rifle', 'email', '".$ourprice."')");

The '$decodedfile' is simply the json_decode'd data.json.

So, my real question is, why when I cast it to a float does it become 0?

  • Have you tried `var_dump($tmp)` to see what it contains? – Barmar Jan 31 '15 at 20:09
  • 1
    That `preg_replace()` won't extract just the price. It will also include the numbers from the `$` entity. – Barmar Jan 31 '15 at 20:10
  • 1
    Using regular expressions to parse HTML is a bad idea. Use `DOMDocument`. – Barmar Jan 31 '15 at 20:11
  • 1
    Casting with leading garbage will lead to zeros. Apply something like `strip_tags` and `html_entity_decode` prior. Or make your regex more specific. (Also use `\s+` rather than enumerating whitespace minutae.) – mario Jan 31 '15 at 20:12
  • I have fixed the problem (in a way). Now when I cast it, it becomes and integer. '$ourprice = number_format((float)$tmp * 0.75);' – Keillen Hayes Jan 31 '15 at 21:30

1 Answers1

0

Try str_replace to remove &#36; before you do your regular expression, then use [0-9,.]+ for your regular expression in preg_match:

foreach($decodedfile as $datas) {
    $tmp = str_replace("&#36;","", $datas->price)
    $tmp = preg_replace(array("/[0-9,.]+/"), "", $tmp);
    $ourprice = (float)$tmp;
    $sql2 = ("INSERT INTO Products (FileID, FileName, FileCat, FileType, FileMethod, FilePrice) VALUES ('".$id."', '".$datas->name."', '12', 'Rifle', 'email', '".$ourprice."')");
Lil' Bits
  • 898
  • 2
  • 9
  • 24
  • 1
    Just a note, I agree with Barmar. You *should* use `DOMDocument`. http://us1.php.net/manual/en/class.domdocument.php – Lil' Bits Jan 31 '15 at 20:14