1

次のXMLを連想配列に変換/解析する必要があります。PHPのsimplexml_load_string関数を試してみましたが、キー要素として属性を取得しませんでした。

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

1 に答える 1

2

あなたはあなたが望むことを使用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;
}

DOMDocumentまたはXPathをクリックすると、詳細情報が表示されます。

編集

葉のあるノードがあるようです。

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

明らかに、その場合、探しているものを取得するには、この「サブDOM」を再度「ナビゲート」する必要があります。

プラサントの答えも良いですが、キーとしてなどを生成します。あなたが何を望んでいるかはわかりません。

于 2013-02-27T11:23:33.413 に答える