[英]Accessing a specific XML-node with PHP using SimpleXML
最近我在使用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>
具體來說,我需要<value format="hh:mm:ss">
節點的值。
因此,我有一個對該對象的引用,看起來像這樣:
$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
在此先感謝您提供任何有用的建議:)
您的錯誤是過於完全信任var_dump
,而不是嘗試根據手冊中的示例使用元素。
首次嘗試時,您訪問了$duration_node->value
; 可以通過幾種不同的方式使用它:
foreach($duration_node->value as $value_node)
對其進行迭代,則foreach($duration_node->value as $value_node)
獲得每個<value>
元素 $duration_node->value[2]
echo $duration_node->value
與echo $duration_node->value[0]
您的第二個示例運行良好-它找到了帶有屬性format="hh:mm:ss"
的<value>
元素。 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.