PHP从XML属性中读取十进制整数 [英] PHP read decimal integers from xml attributes

查看:17
本文介绍了PHP从XML属性中读取十进制整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PHP编写一个函数,该函数从XML中获取数字,然后将这些数字相乘。但是,我不知道如何在SimpleXML中使用十进制数。

PHP

$xml = new SimpleXMLElement(
'<DOM>
  <TAB id="ID1" width="30.1" height="0.5" ></TAB> 
  <TAB id="ID2" width="15.7" height="1.8" ></TAB>
</DOM>');

foreach ($xml->children() as $second_level) {
    echo $second_level->attributes()->id."<br>";
    echo ($second_level->attributes()->width * 10)."<br>";
    echo ($second_level->attributes()->height * 10)."<br>";
}

当前(错误)输出:

ID1 
300
0
ID2
150
10

正确的输出应为:

ID1
301
5
ID2
157
18

推荐答案

其他答案都在正确的行上,但只是为了明确什么时候需要转换什么,以及因此圆括号需要放在哪里。与PHP中的其他类型不同,SimpleXML对象永远不会自动转换为float,因此像*这样的数学运算符会将它们转换为int。(ifiled this is as a bug,但它被关闭的原因是PHP的内部没有实现它的方法。)

因此,在对其应用任何数学运算之前,您需要将SimpleXML值转换为float(又名double)。为了在没有中间赋值的情况下以正确的顺序强制执行此操作,您将正好需要一组额外的圆括号:((float)$simplexml_value) * $some_number

然而,如Operator Precedence table in the PHP manual所示,诸如(float)之类的类型强制转换的优先级已经高于*,而*的优先级高于.,因此以下代码不需要任何额外的括号(live demo in multiple PHP versions)即可运行

foreach ($xml->children() as $second_level) {
    echo $second_level->attributes()->id . "<br>";
    echo (float)$second_level->attributes()->width * 10 . "<br>";
    echo (float)$second_level->attributes()->height * 10 . "<br>";
}
在强制转换后立即赋值给中间变量也是可行的,因为乘法更愿意将integer10转换为float,而不是将float变量转换为integer(live demo):

foreach ($xml->children() as $second_level) {
    echo $second_level->attributes()->id . "<br>";
    $width = (float)$second_level->attributes()->width;
    echo $width * 10 . "<br>";
    $height = (float)$second_level->attributes()->height;
    echo $height * 10 . "<br>";
}

这篇关于PHP从XML属性中读取十进制整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆