【问题标题】:Accessing a specific XML-node with PHP using SimpleXML使用 SimpleXML 使用 PHP 访问特定的 XML 节点
【发布时间】:2015-02-22 01:39:26
【问题描述】:

最近我在使用 simplexml 时遇到了问题。 我想要做的是获取多次出现的嵌套节点的值。 xml 看起来有点像这样:

<response>
  <album id="123">
  [...]
    <duration>
      <value format="seconds">2576</value>
      <value format="mm:ss">42:56</value>
      <value format="hh:mm:ss">00:42:56</value>
      <value format="xs:duration">PT42M56S</value>
    </duration>
  [...]
  </album>
</response>

具体来说,我需要&lt;value format="hh:mm:ss"&gt; 节点的值。

所以我有一个看起来有点像这样的对象的引用:

$this->webservice->album->duration->value;

现在,如果我 var_dump 这个结果将是:

object(SimpleXMLElement)#117 (5) { 
  ["@attributes"]=> array(1) { 
    ["format"]=> string(7) "seconds" 
  } 
  [0]=> string(4) "2576" 
  [1]=> string(5) "42:56" 
  [2]=> string(8) "00:42:56" 
  [3]=> string(8) "PT42M56S" 
}

我不明白这个输出,因为它采用第一个节点的格式属性(秒)并继续使用数组中的节点值,同时完全忽略以下节点的格式属性。

此外,如果我执行以下操作:

$this->webservice->album->duration->value[2];

结果:

object(SimpleXMLElement)#108 (1) { 
  ["@attributes"]=> array(1) { 
    ["format"]=> string(8) "hh:mm:ss" 
  } 
}

我根本没有要解决的价值。

我也尝试通过以下方式使用 xpath:

$this->webservice->album->duration->xpath('value[@format="hh:mm:ss"]');

导致:

array(1) { 
  [0]=> object(SimpleXMLElement)#116 (1) { 
    ["@attributes"]=> array(1) { 
      ["format"]=> string(8) "hh:mm:ss" 
    } 
  } 
}

所以我的问题是: 我究竟做错了什么? xD

提前感谢任何有用的建议:)

【问题讨论】:

    标签: php simplexml


    【解决方案1】:

    你的错误在于过于完全信任var_dump,而不是尝试使用基于the examples in the manual的元素。

    在您第一次尝试时,您访问了$duration_node-&gt;value;这可以通过几种不同的方式使用:

    • 如果您使用foreach($duration_node-&gt;value as $value_node) 对其进行迭代,您将依次获得每个&lt;value&gt; 元素
    • 您可以通过索引访问特定元素,例如$duration_node-&gt;value[2] 第三个元素
    • 如果您将其视为单个元素,SimpleXML 假定您需要第一个元素,即echo $duration_node-&gt;value 与echo $duration_node-&gt;value[0] 相同

    您的第二个示例运行良好 - 它找到了具有属性 format="hh:mm:ss" 的 &lt;value&gt; 元素。 xpath() 方法总是返回一个数组,所以你需要检查它是否为空然后查看第一个元素。

    一旦您拥有正确的元素,访问其文本内容就像将其转换为字符串 ((string)$foo) 或将其传递给始终需要字符串的内容(例如 echo)一样简单。

    这样就可以了:

    $xpath_results = $this->webservice->album->duration->xpath('value[@format="hh:mm:ss"]');
    if ( count($xpath_results) != 0 ) {
        $value = (string)$xpath_results[0];
    }
    

    这样:

    foreach ( $this->webservice->album->duration->value as $value_node ) {
        if ( $value_node['format'] == 'hh:mm:ss' ) {
            $value = (string)$value_node;
            break;
        }
    }
    

    【讨论】:

    • 感谢您的精彩解释!像魅力一样工作,你是对的。我太依赖 var_dump xD...
    猜你喜欢
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多