如何将嵌套XML解析为嵌套数组?

时间:2011-07-01 06:06:15

标签: php xml arrays soap

如何将此xml传递给数组以在soap函数中使用。喜欢

$res=$client->OTA_HotelDestinationsRQ($myarray);

<OTA_HotelDestinationsRQ Version="1.0">
      <POS>
        <Source>
             <UniqueId Id="username:password" />           
        </Source>
      </POS>
      <DestinationInformation LanguageCode="EN" />
</OTA_HotelDestinationsRQ>

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

function process( DOMNode $node){
    // Special handling for character data
    if( $node instanceof DOMCharacterData){
        return $node->data;
    }

    // Has only text inside:
    if( ($node->childNodes->length == 1) && ($node->childNodes->item(0)->nodeName == '#text') && ($node->childNodes->item(0) instanceof DOMCharacterData)){
        return $node->childNodes->item(0)->data;
    }

    // Get all attributes
    $result = array();
    foreach( $node->attributes as $item){
        $result[ $item->name] = $item->value;
    }

    // Go trough all child nodes
    foreach($node->childNodes as $sub){
        $result[$sub->nodeName] = process( $sub);
    }

    return $result;
}

结果:

Array
(
    [Version] => 1.0
    [POS] => Array
        (
            [Source] => Array
                (
                    [UniqueId] => Array
                        (
                            [Id] => username:password
                        )

                )

        )

    [DestinationInformation] => Array
        (
            [LanguageCode] => EN
        )

    [text] => text
)

有用的文档链接: