[英]How to read values from SimpleXmlElement object in PHP
I found many answers regarding my question but still I'm unable to achieve my goal.我找到了很多关于我的问题的答案,但我仍然无法实现我的目标。 I've a API endpoint which returns me this :
我已经返回了我一个API端点此:
I want to read all the data returned by the API.我想读取 API 返回的所有数据。 Here is my code:
这是我的代码:
<?php
$xml=json_decode(json_encode(file_get_contents('http://ecarrefour.com/test/api/saveProducts.php')),true);
$val= $xml->availability;
echo $val;
?>
I'm getting the following error:我收到以下错误:
Trying to get property of non-object in C:\xampp\htdocs\work\index.php on line 4
Any help would be appreciated.任何帮助,将不胜感激。
There are a couple of problems with your code that I can notice:我可以注意到您的代码有几个问题:
First issue is the true parameter passed to json_decode, which will decode the JSON to array and NOT object.第一个问题是传递给 json_decode 的 true 参数,它将把 JSON 解码为数组而不是对象。 json_decode decodes by default to object, but if you pass true as the second parameter you get an array.
json_decode 默认解码为对象,但如果您将 true 作为第二个参数传递,则会得到一个数组。
That's why you get the error message, as in your situation $xml is an array.这就是您收到错误消息的原因,因为在您的情况下 $xml 是一个数组。
The other issue I'm noticing is the output of the API script.我注意到的另一个问题是 API 脚本的输出。 That output looks like print_r output, which is not correct.
该输出看起来像 print_r 输出,这是不正确的。
Here's what you need to do:您需要执行以下操作:
$xml = simplexml_load_string($xml_string);
That should do the trick.这应该够了吧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.