PHP——数字字符串值的 int 类型转换,给出 0
好的,我正在另一台服务器上查询一个页面,该页面返回两个值的逗号分隔列表。它返回的结果是:
850,640
我有一些 PHP 代码调用该页面上的 file_get_contents ,并且需要根据这两个值进行一些数字计算。
无论我尝试什么,我似乎都无法从中获得 int
值。
$res = trim(file_get_contents('http://thatURL/'));
echo "X" . $res . "X<br/>";
list($x,$y) = array_map(create_function('$a', 'return (int)$a;'), explode(',', $res));
echo "X:$x";
输出结果:
X 850,640 X
X:0
注意逗号分隔值之前和之后的空格(到底是怎么回事?我 trim
'd 它们!)并且 $x
被分配了值 <代码>0。
我在这里做错了什么?
OK, so there is a page I'm querying on another server that returns a comma separated list of two values. Something it would return would be:
850,640
I have some PHP code that calls file_get_contents on that page and needs to do some numeric calculations based on the two values.
No matter what I try, I can't seem to get an int
value out of this.
$res = trim(file_get_contents('http://thatURL/'));
echo "X" . $res . "X<br/>";
list($x,$y) = array_map(create_function('$a', 'return (int)$a;'), explode(',', $res));
echo "X:$x";
results in the output:
X 850,640 X
X:0
Note the spaces before and after the comma separated values(how the hell? I trim
'd them!) and that $x
is assigned the value 0
.
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,没有什么表明 $res 的内容与您所期望的不完全一样。您能否将第一个 echo 更改为:
我的猜测是 $res 包含一些未打印的字符,例如,它实际上是:
或
Nothing, as far as I can see, which indicates that the content of $res is not quite what you expect. Could you change the first echo to:
My guess is $res contains some un-printed characters, for example, it is actually:
or
尝试以下操作。 array_map 和 llamda 函数对于您的使用来说可能有点过分了。
为我工作,但我没有使用
file_get_contents()
。如果这不起作用,则页面正在输出其他内容。Try the following. The
array_map
and llamda function are arguably overkill for your usage.Worked for me, but I'm not using
file_get_contents()
. If that doesn't work, something else is being output by the page.PHP 不是一种类型语言。使用 intval 将字符串转换为整数。
更正:它是一种松散类型的语言!我就是这个意思!
PHP is not a typed language. Use intval to convert a string to integer.
Correction: it is a loosely typed language! That's what I meant!
由于我在 URL 上使用了
file_get_contents()
,因此还放入了一些 HTML,但我在echo
中没有注意到,因为它被解析了...只是空的 body 和 html 标签。哎呀!Since I was using
file_get_contents()
on a URL, there was some HTML being put in as well that I didn't notice in myecho
because it parsed out... just empty body and html tags. Oops!