doutang1873 2019-03-03 10:26
浏览 65
已采纳

PHP XML - 返回错误值

currently I'm working on one e-commerce project. I have XML full of products that I need to implement on the e-shop.

The problem is that my XML parser returns bad values, example: I have float 32 000, 00 and it parse only 32 to my php variable. The number that I'm parsing is somehow divided by thousand and I don't know why. Exactly same code just with XML file that has 32 000 works fine. Are they any convert setting that I need to set while initializing SimpleXML object?

Thanks for help.

  • 写回答

1条回答 默认 最新

  • douchunji1885 2019-03-03 10:37
    关注

    Lets look at this

    I have float 32 000, 00 and it parse

    No you have a string of "32 000, 00". So if we look at how PHP does type juggling

    http://php.net/manual/en/language.types.type-juggling.php

    We see a few examples like this:

    $foo = 5 * "10 Little Piggies"; // $foo is integer (50)
    

    So the value of these 2 multiplied is 50 or 5*10 the ten is parsed from "10 Little Piggies". PHP will apply the same rules to what you have above which results in 32. Because it's a string with those spaces PHP will do it almost exactly the same way as above.

    You can easily test this:

    echo floatval('32 000, 00');
    

    Output

    32 
    

    Sandbox

    You may have to manually convert that to what it should be. One easy thing to do is just remove the spaces:

      echo floatval(str_replace([' ',','], ['','.'], '32 000, 00'));
      #output 32000
      echo floatval(str_replace([' ',','], ['','.'], '32 290,01'));
      #output 32290.01
    

    If I remember right some countries use the , as the . for decimal seperator. But I had to replace the , with . to get them to work... There may be some edge cases where this won't work, but without a bigger sample of data I can't say for sure.

    Where or why those spaces are in there, I have no idea. It would be better to remove them from the XML entirely, but that may not be possible.

    Without some actual code in the question, that's the best I can do.

    Cheers!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog