1

我有一个问题,答案肯定很简单,但我只是缺乏理解。

我有一个具有以下外观的 xml 文件(简短示例)

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

我的问题是,我想从 id 为 1234 的一项中读取所有属性,并在数组中读取其属性和值(如果存在)。

我知道如何使用 xpath 访问特定项目。(感谢这个精彩的 stackoverflow 社区 :))

但是我怎样才能只对某个项目使用 children() 函数呢?

像这样

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

非常感谢!

4

2 回答 2

6

我希望这可以帮助你。

代码

$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";
    }
}

输出

country_id
rc_maintenance_other
claim_right_shareholder
charges_other
other_expenses_heating
unpaid_bills_amount
iv_person_phone

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

于 2013-04-17T07:59:04.123 回答
1

但是我怎样才能只对某个项目使用 children() 函数呢?

SimpleXMLElement::children()Docs方法总是用于 Simplexml 中的某个元素。所以你可以通过使用它来做到这一点。

$element->children();

手册以这种方式铸造它:

查找给定节点的子节点

于 2013-04-17T07:52:42.547 回答