foreach仅显示第一个xml节点的属性

时间:2014-07-31 21:29:27

标签: php xml simplexml

我正在尝试显示属性global_ivr_variable:

$xml = '
  <response method="switchvox.ivr.globalVariables.getList">
      <result>
           <global_ivr_variables>
               <global_ivr_variable id="1" name="cid_name" value="Smith" />
               <global_ivr_variable id="2" name="Q_ID_Global" value="COS" />
           </global_ivr_variables>
      </result>
  </response>
';

$sxml = simplexml_load_string($xml);

foreach($sxml->result->global_ivr_variables->global_ivr_variable->attributes() as $a => $b)
{
echo $a .'=' . $b . "<br>";
}

我得到的只是第一个节点的属性:

id="1"
name="cid_name"
value="Smith"

我也尝试了以下内容,它根本没有给我任何价值......

    foreach($sxml->result->global_ivr_variables as $xvar)
    {
     $a = $xvar->global_ivr_variable->id;
     $b = $xvar->global_ivr_variable->name;
     $c = $xvar->global_ivr_variable->value;
     echo 'a='.$a.', b='.$b.', c='.$c.'<br>';
    }

a=, b=, c=

感谢所有帮助有需要的人!

2 个答案:

答案 0 :(得分:2)

你几乎拥有它,但你需要遍历每个<global_ivr_variable>元素,然后提取属性:

foreach($sxml->result->global_ivr_variables->global_ivr_variable as $variable)
{
    foreach($variable->attributes() as $a => $b)
    {
        echo $a .'=' . $b . "<br>";
    }
}

答案 1 :(得分:0)

如果您使用PHP变量,那些问题通常很容易消失,因为您的代码更具可读性。

此外,您可以通过array-notation访问SimpleXML中的属性:

$variables = $sxml->result->global_ivr_variables->global_ivr_variable;

foreach ($variables as $variable)
{
    printf("%s = %s\n", $variable['name'], $variable['value']);
}

这给出了以下输出:

cid_name = Smith
Q_ID_Global = COS

如前所知,您需要查找哪些属性,使用这些名称可以使代码更清晰,更稳定。

但是,如果您正在寻找 global_ivr_variable 元素的所有属性,那么使用XPath迭代它们会更容易:< / p>

$allAttributes = $sxml->xpath('//global_ivr_variable/@*');

foreach ($allAttributes as $attribute) {
    printf("%s = %s\n", $attribute->getName(), $attribute);
}

然后给出以下输出:

id = 1
name = cid_name
value = Smith
id = 2
name = Q_ID_Global
value = COS

以下是完整的代码示例:

$xml = <<<XML
<response method="switchvox.ivr.globalVariables.getList">
    <result>
        <global_ivr_variables>
           <global_ivr_variable id="1" name="cid_name" value="Smith" />
           <global_ivr_variable id="2" name="Q_ID_Global" value="COS" />
        </global_ivr_variables>
    </result>
</response>
XML;

$sxml = simplexml_load_string($xml);

$variables = $sxml->result->global_ivr_variables->global_ivr_variable;

foreach ($variables as $variable)
{
    printf("%s = %s\n", $variable['name'], $variable['value']);
}

echo "----\n";

$allAttributes = $sxml->xpath('//global_ivr_variable/@*');

foreach ($allAttributes as $attribute) {
    printf("%s = %s\n", $attribute->getName(), $attribute);
}