如何使用邮政编码获得英国地区?

时间:2016-09-12 09:19:09

标签: php json curl

我希望根据使用PHP提供的邮政编码获取英国地区。我写成$ ch = curl_init();

$post="PR3 0SG";

curl_setopt($ch,CURLOPT_URL,  "https://api.postcodes.io/postcodes/$post");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_POST, TRUE);

//curl_setopt($ch, CURLOPT_POSTFIELDS, "limit=1");

$buffer = curl_exec($ch);

if(empty ($buffer))
{ 
   echo " buffer is empty "; 
}
else
{ 
   echo $buffer; 
}

curl_close($ch); 

我得到“缓冲区为空”的消息。 这有什么问题!是否有其他方式或脚本可以使用邮政编码来获取英国地区?我可以提供。

1 个答案:

答案 0 :(得分:0)

  1. 您没有在任何地方初始化curl对象($ch),您需要在实际使用之前执行此操作。
  2. 您正在发送POST请求,此API端点适用于GET

    <?php
    $post = "PR3 0SG";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.postcodes.io/postcodes/$post");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
    $buffer = curl_exec($ch);
    if (empty ($buffer)) {
        echo " buffer is empty ";
    } else {
        echo $buffer;
    }
    
    curl_close($ch);
    
  3. 结果:

    {"status":200,"result":{"postcode":"PR3 0SG","quality":1,"eastings":351012,"northings":440283,"country":"England","nhs_ha":"North West","longitude":-2.74625152521674,"latitude":53.8564534479741,"parliamentary_constituency":"Wyre and Preston North","european_electoral_region":"North West","primary_care_trust":"North Lancashire Teaching","region":"North West","lsoa":"Wyre 006A","msoa":"Wyre 006","incode":"0SG","outcode":"PR3","admin_district":"Wyre","parish":"Myerscough and Bilsborrow","admin_county":"Lancashire","admin_ward":"Brock with Catterall","ccg":"NHS Lancashire North","nuts":"Lancaster and Wyre","codes":{"admin_district":"E07000128","admin_county":"E10000017","admin_ward":"E05009934","parish":"E04005340","ccg":"E38000093","nuts":"UKD44"}}}