【问题标题】:How to pass array values to php variables?如何将数组值传递给php变量?
【发布时间】:2019-08-18 16:18:25
【问题描述】:

我正在为我们当前的运输管理系统开发一个非常小的更新。我应该构建一个 php 脚本来使用来自 USPS 的 AddressValidate API 来基本上使用给定的地址,并使用 USPS 对其进行验证。当然,USPS 会将格式正确的地址作为数组返回。我的问题是,如何将返回的值转换为每个字段的变量? (即地址 1、地址 2、城市等),然后将结果回显如下

地址 1: 123 Happyville Lane
城市: 匹兹堡

我当前的脚本:(我的详细信息已被 * 掩盖)

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

返回的数组如下:

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

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

)

【问题讨论】:

  • 我不明白为什么这个问题有一个 VB.NET 标记。
  • 哎呀!那是个错误。我不知道如何改变它。 :P

标签: php xml api usps


【解决方案1】:
echo "Address1: ".$array_data["Address"]["Address2"]."<br>";
echo "City: ".$array_data["Address"]["City"] //wrong city in example :P

应该做的伎俩 或者如果有更多地址:

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
}

【讨论】:

  • 非常感谢!我知道这对你来说可能超级简单,但我一直在研究一整天,找不到我一生的答案哈哈!
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
相关资源
最近更新 更多