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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献