【问题标题】:simpleXmlElement losses attributes on PHPPHP 上的 simpleXmlElement 丢失属性
【发布时间】:2016-02-27 00:12:02
【问题描述】:

我正在尝试使用如下代码将一些 xml 数据转换为 json:

$xml = file_get_contents($query);
$GSP = new SimpleXMLElement($xml);
echo json_encode($GSP);

问题是,在 SimpleXMLElement 期间,我丢失了 xml 文件中的属性。

这是一个来自 XML 的示例;

<ENTOBRESULTS>
<OBRES module_name="ModName">
  <provider>ModName</provider>
  <title>...</title>
  <MODULE_RESULT>
    <U>    http://someURL.aspx    </U>
    <Title>    AnotherTitle   </Title>
    <Field name="Main">ASD</Field>
    <Field name="ProductType">type</Field>
    <Field name="buttonText">Press it</Field>
    <Field name="buttonUrl">https://anotherURL.aspx</Field>
  </MODULE_RESULT>
</OBRES>
</ENTOBRESULTS>

但是当我将 $GSP 记录到 chrome 控制台时,它会显示如下内容:

ENTOBRESULTS: Object
OBRES: Array[3]
  0: Object
    @attributes: Object
    MODULE_RESULT: Array[3]
      0: Object
        Field: Array[22]
          0: "ASD"
          1: "type"
          2: "Press it"
          3: "https://anotherURL.aspx"

如您所见,我在 $GSP = new SimpleXMLElement($xml) 操作期间丢失了“名称”属性。有没有办法防止这种情况?或者我该如何绕过这个问题?

【问题讨论】:

  • {"OBRES":{"@attributes":{"module_name":"ModName"},"provider":"ModName","title":"...","MODULE_RESULT":{"U":" http:\/\/someURL.aspx ","Title":" AnotherTitle ","Field":["ASD","type","Press it","https:\/\/anotherURL.aspx"]}}} 这是网络浏览器输出的内容!!!!
  • 那你要怎么输出??

标签: php xml


【解决方案1】:

您必须遍历每个 xml 节点,访问属性,并构建您最终将编码为 json 的最终对象。

例子

$xml = file_get_contents('xml.xml');
$GSP = new SimpleXMLElement($xml);


foreach ($GSP->OBRES->MODULE_RESULT->Field as $f){

    //var_dump($f);

    print $f->attributes() . ":" . $f . PHP_EOL;

}

Main:ASD
ProductType:type
buttonText:Press it
buttonUrl:https://anotherURL.aspx

【讨论】:

  • 嗨,Alex,感谢您的回复我得到了相同的值 $f->attributes() 和 $f Main:Main ProductType:ProductType 我怎样才能得到 $f 值?
  • 你不应该得到相同的值,$f 是节点,访问时它会给出值。使用您的 foreach 循环更新问题,以便我们查看。
猜你喜欢
  • 2014-09-24
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多