Trying to get a non-object property of SimpleXML?

I am currently using the following code to extract 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 returns this error.

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

line 132:

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

I have verified that the generated URL is correct. The xml document in question is here (I simplified it for 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?

+5
source share
1 answer

Looking at examples on PHP.net, I believe that you need to make this access:

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

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

+4
source

All Articles