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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作