循环遍历XML对象的字段值PHP

时间:2017-03-13 14:23:44

标签: php xml string simplexml

我有一个看起来像这样的XML ......

<fields>
  <field>
    <id>86</id>
    <source>system</source>
    <type>integer</type>
    <name>bounce_count</name>
    <label>Bounce count</label>
    <validation/>
    <store-locally>true</store-locally>
    <display-in-profile>false</display-in-profile>
    <include-in-export>false</include-in-export>
    <lma_display>false</lma_display>
    <newsletters></newsletters>
  </field>
</fields>

我需要循环遍历<field>内的每个标记的值。我尝试了以下(结果是XML),首先我得到了字段标记内的所有内容......

$value = $result->field
$value = simplexml_load_string($value);

如果我var_dump()这看起来如此......

  

object(SimpleXMLElement)#47(11){[&#34; id&#34;] =&gt; string(3)&#34; 153&#34; [&#34;源&#34;] =&GT; string(6)&#34; client&#34; [&#34;类型&#34;] =&GT; string(6)&#34; string&#34; [&#34;名称&#34;] =&GT; string(4)&#34; name&#34; [&#34;标签&#34;] =&GT; string(4)&#34; Name&#34; [&#34;验证&#34;] =&GT; object(SimpleXMLElement)#48(0){} [&#34; store-local&#34;] =&gt; string(4)&#34; true&#34; [&#34;显示在简档&#34;] =&GT; string(4)&#34; true&#34; [&#34;包括式出口&#34;] =&GT; string(4)&#34; true&#34; [&#34; lma_display&#34;] =&GT; string(4)&#34; true&#34; [&#34;通讯&#34;] =&GT; object(SimpleXMLElement)#46(0){}}

接下来,我尝试循环遍历field

中的字段
foreach ($value as $single_field) {
    echo $single_field;
}

但我没有输出。如果我var_dump() $single_field我得到与上面相同的结果。我需要遍历每个字段中的值。因此,对于上面的XML,我需要存储以下值...

86
system
integer
bounce_count
Bounce Count
true
false
false
false

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果您尝试迭代元素的子元素,则需要在foreach循环中使用SimpleXMLElement::children

foreach ($value->children() as $single_field) {
    echo $single_field . "\n";
}