Trying to get property of non-object SimpleXML?

2019-02-22 22:59发布

I am currently using the following code to retrieve information from a REST api.

$url = "http://api.remix.bestbuy.com/v1/products%28upc=".$upc."%29?apiKey=(API KEY)";

$xmlfiledata = file_get_contents("$url");

$xmldata = new SimpleXMLElement($xmlfiledata);

$saleprice = $xmldata->products->product->salePrice;
echo $saleprice;

However, PHP is returning this error.

Notice: Trying to get property of non-object in FILE LOCATION on line 132

line 132 is:

$saleprice = $xmldata->products->product->salePrice;

I have verified that the URL being produced is correct. The xml document in question is here (I simplified it for the sake of simplicity).

<products currentPage="1" totalPages="1" from="1" to="1" total="1" queryTime="0.006" totalTime="0.014" canonicalUrl="/v1/products(upc="635753489873")?apiKey=xr2r8us3dcef7qdjnecbvh6g" partial="false">
<product>
<salePrice>529.99</salePrice>
</product>
</products>

How to fix?

标签: php simplexml
1条回答
聊天终结者
2楼-- · 2019-02-22 23:18

Looking at the examples on PHP.net, I believe you'd need to do the access like this:

$saleprice = $xmldata->product[0]->salePrice;

$xmldata is actually your "products" level, so I don't think you need ...->products->...

查看更多
登录 后发表回答