2016-08-13 158 views
1
<?xml version="1.0" encoding="UTF-8"?> 
    <abc-response> 
    <error-messages> 
    <errors code="302"> 
     User does not have access to this Product 
    </errors> 
    </error-messages> 
</abc-response> 

上午使用simplexml_load_string並使用屬性函數來獲取代碼,並且我不斷得到空值。從xml文件獲取屬性php

$results = simplexml_load_string($response); 

$errorCode = $results->attributes()->{'errors'}; 

回答

3

您需要導航到具有所需屬性的元素。有很多方法。

echo $results->{'error-messages'}->errors['code'];//302 

這只是正常,因爲這裏只有一個error-messages和一個errors。如果你有幾個,你可以使用數組符號來表示你想要的。所以,下面的線也呼應302

echo $results->{'error-messages'}[0]->errors[0]['code']; 

你甚至可以使用xpath,查詢語言來遍歷XML。該//將按名稱返回所有節點:

echo $results->xpath('//errors')[0]->attributes()->code; //302 

echo顯示了一些,但它仍然是一個對象。如果你想拍攝只是整數,鑄像這樣:

$errorCode = (int) $results->{'error-messages'}->errors['code']; 

看看這個really helpful intro

+0

謝謝效果很好 – mululu