2013-02-27 85 views
1

我需要將以下XML轉換/解析爲關聯數組。我嘗試了PHP的simplexml_load_string函數,但它沒有檢索屬性作爲關鍵元素。如何將XML數據作爲具有屬性的關聯數組作爲關鍵字PHP

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<OPS_envelope> 
<header> 
    <version>0.9</version> 
</header> 
<body> 
    <data_block> 
    <dt_assoc> 
    <item key="protocol">XCP</item> 
    <item key="object">DOMAIN</item> 
    <item key="response_text">Command Successful</item> 
    <item key="action">REPLY</item> 
    <item key="attributes"> 
    <dt_assoc> 
     <item key="price">10.00</item> 
    </dt_assoc> 
    </item> 
    <item key="response_code">200</item> 
    <item key="is_success">1</item> 
    </dt_assoc> 
    </data_block> 
</body> 
</OPS_envelope> 

我需要這樣上面的XML數據,密鑰=>值對。

array('protocol' => 'XCP', 
    'object' => 'DOMAIN', 
    'response_text' => 'Command Successful', 
    'action' => 'REPLY', 
    'attributes' => array(
     'price' => '10.00' 
    ), 
    'response_code' => '200', 
    'is_success' => 1 
) 
+0

試試這個@json_decode(@json_encode($ object),1); – sanj 2013-02-27 11:25:14

回答

1

你可以使用DOMDocumentXPath做你想做什麼:

$data = //insert here your xml 
$DOMdocument = new DOMDocument(); 
$DOMdocument->loadXML($data); 
$xpath = new DOMXPath($DOMdocument); 
$itemElements = $xpath->query('//item'); //obtain all items tag in the DOM 
$argsArray = array(); 
foreach($itemElements as $itemTag) 
{ 
    $key = $itemTag->getAttribute('key'); //obtain the key 
    $value = $itemTag->nodeValue; //obtain value 
    $argsArray[$key] = $value; 
} 

你可以找到更多的信息,點擊DOMDocumentXPath

編輯

我看到你有一個有葉子的節點。

<item key="attributes"> 
    <dt_assoc> 
     <item key="price">10.00</item> 
    </dt_assoc> 
</item> 

顯然,在這種情況下,你必須「導航」這個「子DOM」再次獲得你在找什麼。

Prasanth答案也不錯,但會產生等等作爲關鍵,我不知道是不是你想要的。

相關問題