简体   繁体   中英

How to pass array values to php variables?

I am developing a very small update to our current shipping management system. I am supposed to build a php script to use the AddressValidate API from USPS to essentially use a given address, and validate it with USPS. Of course, USPS will return the correctly formatted address as an array. My question is, how do I convert the returned values into variable for each field? (ie. address1, address2, city, etc) and then echo that result as the following

Address1: 123 Happyville Lane
City: Pittsburgh

My current script: (my details have been masked with *)

<?php
$user = '****';
$xml_data = "<AddressValidateRequest USERID='$user'>" .
"<IncludeOptionalElements>true</IncludeOptionalElements>" .
"<ReturnCarrierRoute>true</ReturnCarrierRoute>" .
"<Address ID='0'>" .
"<FirmName />" .
"<Address1>123 happyville lane</Address1>" .
"<Address2></Address2>" .
"<City>columbus</City>" .
"<State>ohio</State>" .
"<Zip5></Zip5>" .
"<Zip4></Zip4>" .
"</Address>" .
"</AddressValidateRequest>";



$url = "http://production.shippingapis.com/ShippingAPI.dll?API=Verify";


    //setting the curl parameters.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // Following line is compulsary to add as it is:
    curl_setopt($ch, CURLOPT_POSTFIELDS,
                'XML=' . $xml_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
    $output = curl_exec($ch);
    echo curl_error($ch);
    curl_close($ch);


print_r('<pre>');
print_r($array_data);
print_r('</pre>');
echo PHP_EOL;

The returned array is as follows:

Array
(
    [Address] => Array
        (
            [@attributes] => Array
                (
                    [ID] => 0
                )

            [Address2] => 123 HAPPYVILLE LANE
            [City] => COLUMBUS
            [State] => OH
            [Zip5] => 12345
            [Zip4] => 1849
            [DeliveryPoint] => 18
            [CarrierRoute] => AC016
        )

)
echo "Address1: ".$array_data["Address"]["Address2"]."<br>";
echo "City: ".$array_data["Address"]["City"] //wrong city in example :P

should do the trick or if theres more addresses :

foreach($array_data as $key=>$address){
    $address2=$array_data["Address"]["Address2"];//if you need the assignment
    echo "Address1: ".$address2."<br>";
    echo "City: ".$array_data["Address"]["City"] //wrong city in example :P
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM