Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get property of non-object SimpleXML?

Tags:

php

simplexml

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?

like image 425
01jayss Avatar asked Oct 11 '22 01:10

01jayss


1 Answers

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->...

like image 113
afuzzyllama Avatar answered Oct 13 '22 01:10

afuzzyllama