PHP Simplexml中的基础数学

PHP Simplexml中的基础数学,php,simplexml,Php,Simplexml,下面的代码是用PHP编写的,从XML响应文件返回价格 $price = $result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice; //lowest new price $listPrice = $result->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice; //l

下面的代码是用PHP编写的,从XML响应文件返回价格

$price = $result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice; //lowest new price 
$listPrice = $result->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice; //list price
如果我回显$price或$listPrice,它会起作用

我希望得到这两个价格之间的差额,但如果我这样做,我将得到零

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

欢迎提供任何帮助

我假设$price和$listprice是数字(整数或双精度),因此单独回显它们时可能看起来是数字,但它们可能是带空格的字符串,这会阻止对它们进行解析。尝试使用trim()删除空白(例如,$price=trim($price))。

我假设$price和$listprice是数字(整数或双精度),因此单独回显它们时可能看起来是数字,但它们可能是带空格的字符串,这会阻止对它们进行分析。尝试使用trim()删除空白(例如,$price=trim($price))。

虽然它们可能看起来是数字,但将它们转换为浮点数可能是值得的,只是为了确保这一点

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

虽然它们看起来可能是数字,但为了确保这一点,将它们放到浮动中可能是值得的

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

您很可能试图从字符串中减去字符串。您需要将值转换为数字类型。如果您使用的是价格,您可能需要浮点数:

$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;

您很可能试图从字符串中减去字符串。您需要将值转换为数字类型。如果您使用的是价格,您可能需要浮点数:

$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;

您可以使用is_numeric()测试$price和$listPrice是否为数字。
is_numeric
几乎从来都不是您想要的函数,因为它接受类似
1.5e10
(科学记数法)的内容。诚然,根据输入情况,在这里可能是合适的,但人们通常在应该使用
ctype\u digit
(检查字符串是否完全由数字组成)时使用它。您可以使用is\u numeric()测试$price和$listPrice是否为数字。
is\u numeric
几乎从来都不是您想要的函数,因为它接受像
1.5e10
(科学记数法)这样的东西。诚然,根据输入的不同,它在这里可能是合适的,但人们通常在应该使用
ctype\u digit
时使用它(检查字符串是否完全由数字组成)。