如何从 php 调用 json


How to call json from php

我写了一个php代码,应该打印json调用的响应。但是我得到空输出。我已经检查了我的 json 调用是否从 restclient 工作正常。

这是我的代码

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

提前谢谢。

尝试:

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

好的,所以我解决了我的问题并重写了代码。我实际上没有在json字段中提供正确形式的用户名和密码,这确实是一个愚蠢的错误。我在这里提供更新的代码`

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

?>`

谢谢大家。