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 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建