douzhongjian0752 2013-12-28 23:17
浏览 28
已采纳

使用simplexml在XML对象中复制数组名称

I am using simplexml to load an XML file and encode the content in JSON format so that it can be consumed by another part of my application. Everything works fine but I noticed that simplexml generates singular names for "arrays", for instance, this piece of XML:

<employees>
    <employee>
        <name>John M.</name>
        <age>34</age>
    </employee>
    <employee>
        <name>Sarah J.</name>
        <age>31</age>
    </employee>
</employees>

Once that I load the XML code in a PHP object using:

$xml = simplexml_load_file("employees.xml");

I have to use the singular form for access the arrays of employees, for instance:

$xml->employee[1];

But I want to pluralize names of arrays. The major reason for doing this is because I want to generate JSON from that XML object directly using json_encode, rather than generating a new array/object with the respective name pluralized.

It is possible to change this behavior? If this cannot be accomplished within simplexml how would be the best approach to resolve this?

  • 写回答

2条回答 默认 最新

  • dongyuan1983 2013-12-28 23:34
    关注

    It is possible to change this behavior?

    Short answer: no.


    You're going to want to "generate [something] with the respective name pluralized". In any case, I would advise against simply json_encode()-ing SimpleXMLElement objects anyway.

    In the long run (and in your case, it seems, the short run) you'd be better off:

    • changing the XML document to have pluralised element names
    • or, doing some work yourself as an intermediate step between SimpleXML and json_encode()

    As for "the best approach" (for serializing anything as JSON), I would advise going for your own class (perhaps extending SimpleXMLElement) that implements the JsonSerializable interface. Other options include changing the XML as mentioned above, or building your own array/object structure to JSON encode, to name a few.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里