Basic mathematics in PHP Simplexml

て烟熏妆下的殇ゞ 提交于 2019-12-11 18:09:29

问题


The code below is in PHP and returns prices from a XML response file.

$price = $result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice; //lowest new price 
$listPrice = $result->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice; //list price

If I echo $price or $listPrice it works

I wish to get the difference between the two prices but I am getting NULL if I do

$savings = $listPrice - $price; or $savings = ($listPrice - $price);

Any assistance is welcome


回答1:


You're most likely trying to subtract a string from a string. You need to convert the values to a numeric type. If you're working with prices, you'll probably want floating point numbers:

$price = floatval($result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice); //lowest new price 
$listPrice = floatval($result->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice); //list price

$savings = $listPrice - $price;



回答2:


I assume $price and $listprice are numbers (integers or doubles), so it is possible they appear to be numbers when echoing them alone, but they could be strings with whitespace that is preventing them from being parsed. Try using trim() to remove whitespace (eg, $price = trim($price)).




回答3:


While they may appear to be numbers, it may be worth it to cast them to floats, just to make sure.

$savings = floatval($listPrice) - floatval($price);


来源:https://stackoverflow.com/questions/16001102/basic-mathematics-in-php-simplexml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!