试图获得非对象SimpleXML的属性



我目前使用以下代码从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;

但是,PHP返回这个错误。

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

第132行是:

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

我已经验证了生成的URL是正确的。所讨论的xml文档在这里(为了简单起见,我对其进行了简化)。

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

如何修复?

看看PHP.net上的例子,我相信你需要这样做访问:

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

$xmldata实际上是你的"产品"级别,所以我认为你不需要...->products->...

最新更新