0

When I am using the below code then I am getting all the data printed

<?php
$url = "https://api.postalpincode.in/pincode/201301";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
$xmldata = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_r($xmldata);
?>

But I am not able to know that if only one of these data is to be printed then how will we do it?

for example, I want to print only the district in this enter image description here

1 Answers1

0

This works for me:

<?php

$url = "https://api.postalpincode.in/pincode/201301";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);

$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$json = json_decode($response, true);
$districts = [];
foreach($json as $item) {
    foreach($item['PostOffice'] as $office) {
        $districts[] = $office['District'];
    }
}


print_r($districts);

and the result is

Array
(
    [0] => Gautam Buddha Nagar
    [1] => Gautam Buddha Nagar
    [2] => Gautam Buddha Nagar
    [3] => Ghaziabad
)
sensorario
  • 20,262
  • 30
  • 97
  • 159