且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-05 20:09:34

我希望这可以为您提供帮助。



代码

  $ xml = new SimpleXMLElement('< item id = 1234> 
<属性名称= country_id>
< value> 4402< / value>
< / property>
<属性名= rc_maintenance_other>
< / property>
<属性name = claim_right_shareholder>
< / property>
<属性name = charges_other>
< / property>
<属性name = other_expenses_heating >
< /属性>
<属性名称= unpaid_bills_amount>
< / pr操作
<属性名称= 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']。 \n;
}
}

输出


  country_id 
rc_maintenance_other
Claim_right_shareholder
charge_other
other_expenses_heating
unpaid_bills_amount
iv_person_phone


例如: http://sandbox.onlinephpfunctions.com/code/4e0ddba2ed273ab4a20dc9379ea9ed0d669a4c0d

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 *** 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!

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'] ."\n";
    }
}

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