doutang1873 2019-03-03 02: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 02: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!

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部