2013-02-27 22 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答案也不错,但会产生等等作为关键,我不知道是不是你想要的。

相关问题