Mahesh
Mahesh

Reputation: 320

How to get XML data as an associative array with attributes as key in PHP

I need to convert/parse the following XML to an associative array. I tried with PHP's simplexml_load_string function but it didn't retrieve attributes as key element.

<?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>

I need the above XML data like this, key => value pair.

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

Upvotes: 2

Views: 2025

Answers (1)

DonCallisto
DonCallisto

Reputation: 29922

You could use DOMDocument and XPath to do what you want:

$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;
}

You could find more info, clicking on DOMDocument or XPath

EDIT

I see that you have a node that have a leaf.

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

Obviously, in that case, you have to "navigate" this "sub-DOM" again to obtain what you're looking for.

Prasanth answer is also good, but will produce and so on as keys, and I don't know if is what you want.

Upvotes: 3

Related Questions