dsqbh42082 2013-04-17 07:46
浏览 82
已采纳

使用simplexml和php访问某个节点的所有子节点

I have a question and the answer is sure simple, but it just lacks of understanding from my side.

I have a xml file with following look (short example)

<item id="1234">
    <property name="country_id">
        <value>4402</value>
    </property>
    <property name="rc_maintenance_other">
    </property>
    <property name="claim_right_shareholder">
    </property>
    <property name="charges_other">
    </property>
    <property name="other_expenses_heating">
    </property>
    <property name="unpaid_bills_amount">
    </property>
    <property name="iv_person_phone">
        <value>03-6756711</value>
    </property>
</item>
<item id="9876">
   ...
</item>

My problem is, I want to read all propertys from the one item with the id 1234 with their attribute and their value, if exists, in an array.

I know how to access the certain Item with xpath. (Thanks to this wonderful stackoverflow community :) )

But how can I use the children() function only to a certain item?

Like this

foreach ($item[id="1234"]->children() as $property) {

Thank you so much!

  • 写回答

2条回答 默认 最新

  • dongyuluan7494 2013-04-17 07:59
    关注

    I hope this can help you.

    Code

    $xml = new SimpleXMLElement('<item id="1234">
        <property name="country_id">
            <value>4402</value>
        </property>
        <property name="rc_maintenance_other">
        </property>
        <property name="claim_right_shareholder">
        </property>
        <property name="charges_other">
        </property>
        <property name="other_expenses_heating">
        </property>
        <property name="unpaid_bills_amount">
        </property>
        <property name="iv_person_phone">
            <value>03-6756711</value>
        </property>
    </item>');
    
    foreach ($xml->xpath('//item[@id="1234"]') as $item)
    {    
        foreach ($item->children() as $child) {
          echo $child['name'] ."
    ";
        }
    }
    

    Output

    country_id
    rc_maintenance_other
    claim_right_shareholder
    charges_other
    other_expenses_heating
    unpaid_bills_amount
    iv_person_phone
    

    Example: http://sandbox.onlinephpfunctions.com/code/4e0ddba2ed273ab4a20dc9379ea9ed0d669a4c0d

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

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?