doumei1955 2018-05-20 03:22
浏览 99
已采纳

PHP:从XML字符串中获取数据

I have a simple problem getting data from an eBay API string. I want to format numbers to 2 digits 8.0 > 8.00

This works fine

echo $price;  // output: 8.0

But...

echo number_format($price, 2);  // output:   (nothing)

A var_dump tells me why...

var_dump($price);  
// output: object(SimpleXMLElement)#19 (2) { ["@attributes"]=> array(1) { ["currencyId"]=> string(3) "USD" } [0]=> string(3) "8.0" } 

How do I get the 8.0 into a 8.00 (I know I can use REGEX but it feels like not the proper way)

And while we are here, how I can get the 'USD' ?

PS: the API call used is findCompletedItems - and strangely to me, the XML response has no visible USD at all.

  • 写回答

2条回答 默认 最新

  • dongqiangse6623 2018-05-20 11:06
    关注

    The var_dump gives you an object of type SimpleXMLElement which has a __toString method which returns the text content that is directly in the element so echo $price; will result in 8.0

    The USD is part of the attributes which returns an object of type SimpleXMLElement.

    You can get the price and the currency casting it to a (string)

    $priceAsString = (string)$price;
    $currencyIdAsString = (string)$price->attributes()->currencyId;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集