2014-10-22 56 views
2

在我所看到的XML結構的simplexml的所有例子是這樣的:的SimpleXML與多個標籤

<examples> 
<example> 
</example> 
<example> 
</example> 
<example> 
</example> 
</examples> 

但是我處理XML形式:

<examples> 
    <example> 
    </example> 
    <example> 
    </example> 
    <example> 
    </example> 
</examples> 
<app> 
<appdata> 
<error> 
<Details> 
<ErrorCode>101</ErrorCode> 
<ErrorDescription>Invalid Username and Password</ErrorDescription> 
<ErrorSeverity>3</ErrorSeverity> 
<ErrorSource /> 
<ErrorDetails /> 
</Details> 
</error> 
<items> 
<item> 
</item> 
<item> 
</item> 
</items> 
</appdata> 
</app> 

我會喜歡跳過示例的東西,並直接進入應用程序標記,並檢查錯誤錯誤碼是否存在,如果不存在,請轉到items數組並循環。

我處理這個電流的方法是:

$items = new SimpleXMLElement($xml_response); 
foreach($items as $item){ 
     //in here I check the presence of the object properties 
    } 

有沒有更好的辦法?問題是xml結構有時會改變順序,所以我希望能夠直接轉到xml的特定部分。

+2

這不是你正在處理的XML,除非它有共同的根節點。 – dfsq 2014-10-22 11:04:41

回答

1

這種東西很容易用XPath,而且很方便,SimpleXML has an xpath function內置到它裏面! XPath允許您根據祖先,後代,屬性,值等選擇圖中的節點。

下面是使用SimpleXML的xpath函數從XML中提取數據的示例。請注意,我爲您發佈的示例添加了一個額外的父元素,以便XML進行驗證。

$sxo = new SimpleXMLElement($xml); 
# this selects all 'error' elements with parent 'appdata', which has parent 'app' 
$error = $sxo->xpath('//app/appdata/error'); 

if ($error) { 
    # go through the error elements... 
    while(list(, $node) = each($error)) { 
     # get the error details 
     echo "Found an error!" . PHP_EOL; 
     echo $node->Details->ErrorCode 
     . ", severity " . $node->Details->ErrorSeverity 
     . ": " . $node->Details->ErrorDescription . PHP_EOL; 
    } 
} 

輸出:

Found an error! 
101, severity 3: Invalid Username and Password 

這裏是另外一個例子 - 我編輯的XML摘錄略微顯示效果也比較好這裏:

// edited <items> section of the XML you posted: 
<items> 
    <item>Item One 
    </item> 
    <item>Item Two 
    </item> 
</items> 

# this selects all 'item' elements under appdata/items: 
$items = $sxo->xpath('//appdata/items/item'); 
foreach ($items as $i) { 
    echo "Found item; value: " . $i . PHP_EOL; 
} 

輸出:

Found item; value: Item One 
Found item; value: Item Two 

有更多的信息在SimpleXML XPath文檔中,並嘗試zvon.org XPath tutorials - 它們爲XPath 1.0語法提供了良好的基礎。

+0

感謝您的回答。我實際上是在Niloct的推動下自己到達那裏才讓我讀到xpath的。 – 2014-10-22 16:06:57

+1

雖然我選擇了它,但您的答案更有幫助。 – 2014-10-22 16:07:23