如何将SimpleXMLElement对象中的参数分配给变量?

时间:2015-09-23 19:25:52

标签: php object

我使用以下脚本将用户数据发布到支付网关:

$map_url = "https://paynetzuat.atomtech.in/paynetz/epi/fts?login=160&pass=Test@123&ttype=NBFundTransfer&prodid=NSE&amt=50&txncurr=INR&txnscamt=0&clientcode=007&txnid=12345&date=19/09/2015&custacc=1234567890&udf1=vinodBisen&udf2=mymail@gmail.com&udf3=9890933093&udf4=mybillingaddress&ru=http://mysite.in/thankyou.html";

if (($response_xml_data = file_get_contents($map_url))===false) {
    echo "Error fetching XML\n";
} else {
    libxml_use_internal_errors(true);
    $data = simplexml_load_string($response_xml_data);

    if (!$data) {
        echo "Error loading XML\n";
        foreach(libxml_get_errors() as $error) {
            echo "\t", $error->message;
        }
    } else {
        echo '<pre>';
        print_r($data);
        echo '</pre>';
    }
}

得到如下答复:

SimpleXMLElement Object
(
    [MERCHANT] => SimpleXMLElement Object
        (
            [RESPONSE] => SimpleXMLElement Object
                (
                    [url] => https://mysite.api.url.com/fts
                    [param] => Array
                        (
                            [0] => NBFundTransfer
                            [1] => 524014
                            [2] => K30ZsUL2Z5mD8NN1xS6FxIuV0YlOS2e1KPEKv0fT0Ms%3D
                            [3] => 1
                        )    
                )    
        )    
)

我希望将每个响应都放到一个单独的变量中,以使用支付网关API收到的动态响应创建链接。

1 个答案:

答案 0 :(得分:0)

您可以对RESPONSE进行迭代,然后对param进行迭代,通过将其转换为string来提取名称和值:

foreach($data->MERCHANT->RESPONSE as $response) {

    $responseData = array(
        'url' => (string)$response->url
    );

    foreach($response->param as $param) {
        $responseData[(string)$param->attributes()->name] = (string)$param;
    }

    print_r($responseData);
}

输出:

Array
(
    [url] => https://paynetzuat.atomtech.in/paynetz/epi/fts
    [ttype] => NBFundTransfer
    [tempTxnId] => 524142
    [token] => BL%2BmNz1kIv9%2FzTk8ei9iAxNmMGUJtt5jMip9Bfw1hG0%3D
    [txnStage] => 1
)

然后,如果你想回应token,你可以这样做:

echo $responseData['token'];

如果只有一个回复,您可以跳过RESPONSE上的迭代:

$responseData = array(
    'url' => (string)$data->MERCHANT->RESPONSE->url
);

foreach($data->MERCHANT->RESPONSE->param as $param) {
    $responseData[(string)$param->attributes()->name] = (string)$param;
}

print_r($responseData);