简体   繁体   English

如何从 PHP 中的 SimpleXmlElement 对象读取值

[英]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:您需要执行以下操作:

  1. In the API script, don't print_r($simpleXmlObject).在 API 脚本中,不要使用 print_r($simpleXmlObject)。 You can use the asXML method on your simpleXml object to get the XML which you can then output.您可以在 simpleXml 对象上使用 asXML 方法来获取可以输出的 XML。
  2. In your client script, first run file_get_contents to get the needed XML.在您的客户端脚本中,首先运行 file_get_contents 以获取所需的 XML。
  3. You can then create the simpleXML object on the client side from that XML, using something like:然后,您可以使用以下内容在客户端从该 XML 创建 simpleXML 对象:

$xml = simplexml_load_string($xml_string);

  1. Now you can do the json_decode to json_encode trick you're doing above on $xml, to convert it from SimpleXML to array or object.现在,您可以在 $xml 上执行 json_decode 到 json_encode 技巧,将其从 SimpleXML 转换为数组或对象。

That should do the trick.这应该够了吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM