shiny shiny - 1 month ago 6
PHP Question

How to parse JSON URL of REST API using PHP?

$whmcsUrl = "https://test.etravelsmart.com/etsAPI/api/getStations?";
// Admin username and password
$username = "888888888";
$password = "**********";
// Set post values
$postfields = array(
'username' => $username,
'password' => md5($password),
'action' => 'GetClients',
'responsetype' => 'json',
);
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);

// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $whmcsUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$response = curl_exec($ch);
if (curl_error($ch)) {
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);
// Attempt to decode response as json
$jsonData = json_decode($response, true);
// Dump array structure for inspection
var_dump($jsonData);


The above program returns NULL. My JSON format looks like this:

My JSON is placed inside this link
https://test.etravelsmart.com/etsAPI/api/getStations?
. How to connect with this JSON URL and parse that data from the URL?

{
"stationList":[
{"stationName":"10 dol","stationId":-1},
{"stationName":"Chennai","stationId":2666}
],
"apiStatus":{"success":true,"message":"SUCCESS"}
}

Answer
       i got connected with api..my code is..
        <?php 
          $ch = curl_init();
           $url="http://test.etravelsmart.com/etsAPI/api/getStations";
           $username="888888888";
           $password='**********';
           curl_setopt($ch, CURLOPT_URL, $url);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
           curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
           curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
           $output = curl_exec($ch);
           curl_close($ch);


          $someArray = json_decode($output, true);
            foreach( $someArray as $stationList => $array){
          //echo "$stationList  <br />";
           foreach($array as $name => $val){
                //echo "$name  <br />";
            foreach($val as $sname => $value){
           echo "StationName:$value <br />";

         }
          }
        }