简体   繁体   中英

How to call json from php

I have written a php code that should print the response of a json call. But I am getting NULL output. I have checked my json call is working fine from a restclient.

Here is my code

<?php

    $username = "user";
    $password = "password";

    $postData = array(
            'username' => $username,
            'password' => $password,
            'msisdn' => "111111111"
            );

    $ch = curl_init('http://ip:<port>/xxx/yyy/zzz');

    curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);

    // Check for errors
    if($response === FALSE){
    die(curl_error($ch));
    }

    // Decode the response
    $responseData = json_decode($response, TRUE);

    // Print the date from the response
    echo $responseData['published'];

    var_dump($responseData);

    ?>

Thanks in advance.

Try:

$responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new \RuntimeException('Invalid JSON.');
}

okay so i have solved my problem and re-wrote the code. I was actually not providing the correct form of username and password in the json fields which is really a silly mistake. I am giving my updated code here `

$data = array("user" => "$username", "pass" => "$password", "msisdn" => "$msisdn");
$data_string = json_encode($data);

$ch = curl_init('http://ip:port/call_center/account/general');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;


?>`

Thanks everyone.

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